在javascript中用正则表达式过滤指定的字符(一定要能指定!)

来源:百度知道 编辑:UC知道 时间:2024/05/21 20:01:56
就是在前台验证,过滤掉 ' < > ! - 这几个字符.其他字符和汉字都不过滤.如果有非法字符(指定的字符),要能够提示.

楼上的不加转义字符\ 你们搞什么啊
正确的应该是这样的

加入你得到的字符窜为 name
<html>
<head>
<script>
function test1(){
var name=document.getElementById('user').value;
name=name.replace(/(\!+)|(\<+)|(\>+)|(\'+)/g,"");
alert(name);
}
</script>
</head>

<body>
<input type="text" id="user" />
<input type="button" value="te" onclick="test1()">
</body>
</html>

需求描述的不是很明确。

如果只是过滤掉 ' < > ! - 这几个字符,直接
str.replace(/[' < > ! -]/g,"");
就可以了。

如果是判断是否含有这些特殊字符,使用
function check(str){
return /[' < > ! -]/.test(str);
}
就可以,要想提示出来,就调用:

if(check(str)){
//含有非法字符
alert("error");//提示处理,自己扩展吧
}

var str = str.repl