首页 > 代码库 > js中的正则表达式(1)

js中的正则表达式(1)

定义正则表达式规则对象有两种:

1,var reg = /\bis\b/g;   这种情况下\转义作用,\b空格   /*/中的内容就是正则规则

2,var reg = new RegExp("\\bis\\b","g");   有两个\\是因为在js的字符串中\本身也是字符需要转义  通过这种类似构造器的方式定义正则时不需要开始和结尾的//;

举例:

"he is a boy is he".replace(/\bis\b/,"am");
"he am a boy is he"

 

var reg = new RegExp("\\bis\\b","g");
"he is a boy is he".replace(reg,"am");
"he am a boy am he"

字符串的replace方法提供的参数中,第一个参数是正则对象,第二个是要替换成的字符

3中标识符,g全文搜索  i忽略大小写  m多行搜索

举例:

var reg = new RegExp("\\bis\\b","");
"he is a boy is he".replace(reg,"am");
"he am a boy is he"

"he is a boy; IS he".replace(/\bis\b/gi,"am");
"he am a boy; am he"

"he is a boy; IS he".replace(/\bis\b/g,"am");
"he am a boy; IS he"

 

   

js中的正则表达式(1)