js非法字符检测

JavaScript07

js非法字符检测,第1张

1、用RegExp的exec()方法,该方法每次返回一个匹配,找不到时返回null

2、例如,str='1111哈哈    嘿嘿',第一次re.exec(str)返回'哈哈',第二次re.exec(str)返回'嘿嘿',第三次返回null。如下图:

您好

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