[英]Using Javascript Regex For Removing Chars in String
我想创建一个 function 来验证字符串是否存在不正确的字符。
作为第一次尝试,我在数字上进行了尝试。 它适用于 IE9,但不适用于 Chrome 12.0.742.122 和 Firefox 5 和 6
<html>
<head>
<title>Regex Example</title>
<script type="text/javascript">
var regexp;
var input;
var output;
function replaceChars()
{
regexp = "";
output = "";
input = document.getElementById("myinput").getAttribute("value");
regexp = /\d+/g;
output = input.replace(regexp, "");//Remove Digits
setOutput();
}
function setOutput()
{
document.getElementById("myoutput").setAttribute("value", output);
document.getElementById("myexpr").setAttribute("value", regexp);
document.getElementById("myinput").select();
}
</script>
</head>
<body>
Enter : <input type="text" id="myinput" value="" maxlength="25" size="25"/><br/>
RegEx : <input type="text" id="myexpr" value="" maxlength="25" size="25" readonly /><br/>
Output : <input type="text" id="myoutput" value="" maxlength="25" size="25" readonly />
<input type="button" #nClick="replaceChars();" value="Remove Digits"/>
</body>
</html>
regexp = /\w+/g; remove character
regexp = /\w+/i; remove all character lower case and uppercase
regexp = /\D+/i; remove Non digits u can use any thing u wish...
output = input.replace(regexp, "");//Remove Digits
首先,它是onclick
而不是#nClick
。
此外,您可以像这样直接设置属性,而不是getAttribute
/ setAttribute
:
input = document.getElementById("myinput").value;
和
document.getElementById("myoutput").value = output;
然后它在 Chrome 上运行良好: http://jsfiddle.net/Ta6Lw/ 。
你也用过
onClick instead of #nClick
<input type="button" #nClick="replaceChars();" value="Remove Digits"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.