js 正则中的元字符、特殊符号一些例子

JavaScript09

js 正则中的元字符、特殊符号一些例子,第1张

1、正则表达式中的元字符:

代码如下

(

[

{

^

$

|

)

?

*

+

.

例1:

alert(/\?/.test("?"))

例2:

alert(/\\?/.test("?"))

//双重转义,避免按翻译n方式翻译?

2、特殊字符

1.使用ASCII来表示一个字符

指定一个两位的十六进制代码,并在前面加上x,如:x62为b

b字符的ASCII码为98,等于十六进制的62

例1:

代码如下

var

sColor="blue"

var

reB=/\x62/

alert(reB.test(sColor))

142

八进制为b

例2:

代码如下

var

sColor="blue"

var

reB=/\142/

alert(reB.test(sColor))

2.Unicode用u加四位十六进制表示b为0062

例3:

代码如下

var

sColor="blue"

var

reB=/\u0062/

aert(reB.test(sColor))

3.其它特殊字符

特殊字符

字符

描述

t

制表符

n

回车符

r

换页符

a

alert字符

e

escape字符

cX

与X相对应的控制字符

b

回退字符

v

垂直制表符

空字符

您好

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