简体   繁体   English

替换 value 属性中所有出现的“<”、“>”

[英]Replace all occurrences of “<”, “>” inside value attribute

I have the requirement to replace all occurrences of "<" and ">" characters that are found inside the value attribute.我需要替换在 value 属性中找到的所有出现的“<”和“>”字符。 I want to replace "<" and ">" characters with ""我想用“”替换“<”和“>”字符

This is my sample html:这是我的示例 html:

<form name="form1">
<input type="text" value="<first set><second set><third set>" />
<input type="text" value="<fourth set><fifth set><sixth set>" />
</form>

I tried using javascript replace method but no luck.我尝试使用 javascript 替换方法,但没有运气。

You could use this pure JavaScript function:你可以使用这个纯 JavaScript 函数:

 function removeLessGreaterThan(html) { // Use the DOM API to change the value attribute values: var span = document.createElement('span'); span.innerHTML = html; var inputs = span.querySelectorAll('input[type=text]'); for (var i = 0; i < inputs.length; i++) { inputs[i].setAttribute('value', inputs[i].value.replace(/[<>]/g, '')); } return span.innerHTML; } // Sample data: var html = '<form name="form1"> <input type="text" value="Here is a >test<." /> <input type="text" value="And another >test<." /> </form>'; html = removeLessGreaterThan(html); console.log(html);

const FORM_NAME = "form1";

var fields = document.getElementsByName(FORM_NAME)[0].getElementsByTagName("input");

for(var i = 0; i < fields.length; i++) {
    fields[i].value = fields[i].value.replace(/[<>]/g, "");
}

I think you are expecting this way.我想你是这样期待的。 Please go through the code.请通过代码。

 function ReplaceMyValues() { var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i += 1) { if(inputs[i].type=="text") { var currentValue=inputs[i].value.replace(/[<>]/g, ""); inputs[i].value = currentValue; } } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <form name="form1"> <input type="text" value="<first set><second set><third set>" /> <input type="text" value="<fourth set><fifth set><sixth set>" /> <input id="Test" type="button" value="Replace" onclick="ReplaceMyValues();"></input> </form>

你可以使用 jquery

$(".yourInput").val($(".yourInput").val().replace('<', '').replace('>', ''))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM