js 正则过滤特殊字符?

JavaScript016

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

首先要理解这个方法replace。

语法:string.replace(searchvalue,newvalue)

searchvalue:必须。规定子字符串或要替换的模式的 RegExp 对象。

请注意,如果该值是一个字符串,则将它作为要检索的直接量文本模式,而不是首先被转换为 RegExp 对象。  

newvalue:必需。一个字符串值。规定了替换文本或生成替换文本的函数。  

注意RegExp 对象,而// 就是一个RegExp 对象(正则表达式)。

// var RegExp = new RegExp(pattern, attributes)

var reg = new RegExp(' ', 'g')

str = str.replace(reg,'') // 跟str = str.replace(/ /g,'') 是一样意思。

而这里的g是global的缩写,意思是全局匹配

如果没有加g,那么只是匹配第一个就结束了,对应str2,否则就全局匹配,对应str1