简体   繁体   English

使用 Javascript 正则表达式删除字符串中的字符

[英]Using Javascript Regex For Removing Chars in String

I want to create a function that will validate a string for improper chars.我想创建一个 function 来验证字符串是否存在不正确的字符。

As a first try, i tried it on numbers.作为第一次尝试,我在数字上进行了尝试。 It Works on IE9, but not on Chrome 12.0.742.122 and Firefox 5 & 6它适用于 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

First, it is onclick and not #nClick .首先,它是onclick而不是#nClick

Also, instead of getAttribute / setAttribute , you can set attributes directly like this:此外,您可以像这样直接设置属性,而不是getAttribute / setAttribute

input = document.getElementById("myinput").value;

and

document.getElementById("myoutput").value = output;

Then it works fine on Chrome: http://jsfiddle.net/Ta6Lw/ .然后它在 Chrome 上运行良好: http://jsfiddle.net/Ta6Lw/

and also u used你也用过

onClick instead of #nClick
<input type="button" #nClick="replaceChars();" value="Remove Digits"/>

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

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