js 正则过滤特殊字符?

JavaScript012

js 正则过滤特殊字符?,第1张

您好

js检查是否含有非法字符,js 正则过滤特殊字符

//正则

function trimTxt(txt){

 return txt.replace(/(^\s*)|(\s*$)/g, "")

}

 

/**

 * 检查是否含有非法字符

 * @param temp_str

 * @returns {Boolean}

 */

function is_forbid(temp_str){

    temp_str=trimTxt(temp_str)

temp_str = temp_str.replace('*',"@")

temp_str = temp_str.replace('--',"@")

temp_str = temp_str.replace('/',"@")

temp_str = temp_str.replace('+',"@")

temp_str = temp_str.replace('\'',"@")

temp_str = temp_str.replace('\\',"@")

temp_str = temp_str.replace('$',"@")

temp_str = temp_str.replace('^',"@")

temp_str = temp_str.replace('.',"@")

temp_str = temp_str.replace('',"@")

temp_str = temp_str.replace('<',"@")

temp_str = temp_str.replace('>',"@")

temp_str = temp_str.replace('"',"@")

temp_str = temp_str.replace('=',"@")

temp_str = temp_str.replace('{',"@")

temp_str = temp_str.replace('}',"@")

var forbid_str=new String('@,%,~,&')

var forbid_array=new Array()

forbid_array=forbid_str.split(',')

for(i=0i<forbid_array.lengthi++){

if(temp_str.search(new RegExp(forbid_array[i])) != -1)

return false

}

return true

}

---------------------

作者:dongsir 董先生

来源:董先生的博客

原文链接:js检查是否含有非法字符

版权声明:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。转载时请标注:http://dongsir.cn/p/195

varmyReg = /^[a-zA-Z0-9_]{0,}$/ if(!myReg.test(input.val())) {   $.validation.tip(false, input, "用户名不能含有中文或特殊字符")   return } js通过正则表达式限制input输入框只能输入英文字母和数字,不能输入中文。 <input onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"> 文本框中仅允许输入英文字母,小数点,数字,禁止输入中文字符以及其他特殊字符! <input type="text" name="username" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')" /> 输入大于0的正整数 <input onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"> PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用: JavaScript正则表达式在线测试工具: http://tools.jb51.net/regex/javascript 正则表达式在线生成工具: http://tools.jb51.net/regex/create_reg var temp = 'abcdefg Fw:123456 Fw:789.1011' temp =temp.indexOf(‘.’)//匹配某个字符位置 alert(temp)��var temp = 'dsd-5555' temp =temp.replace('-','')//匹配某个字符必替换 alert(temp)

var str=$('#id').val()

var re =/[`~!@#$%^&*_+<>{}\/'[\]]/im

if (re.test(str))

{

alert(存在特殊字符)

}