javascript 正则对象创建 和用法 声明javascript 正则表达式var reCat = new RegExp( "cat ");你也可以var r
声明javascript 正则表达式
var reCat = new RegExp("cat");
你也可以
var reCat = /cat/; //Perl 风格 (推荐)
1) test 检查指定的字符串是否存在
var data = "123123"; var reCat = /123/gi; alert(reCat.test(data)); //true //检查字符是否存在 g 继续往下走 i 不区分大小写 |
2) exec 返回查询值
var data = "123123,213,12312,312,3,Cat,cat,dsfsdfs,"; var reCat = /cat/i; alert(reCat.exec(data)); //Cat |
3)match 得到查询数组
var data = "123123,213,12312,312,3,Cat,cat,dsfsdfs,"; var reCat = /cat/gi; var arrMactches = data.match(reCat) for (var i=0;i < arrMactches.length ; i++) { alert(arrMactches[i]); //Cat cat } |
4) search 返回搜索位置 类似于indexof
var data = "123123,213,12312,312,3,Cat,cat,dsfsdfs,"; var reCat = /cat/gi; alert(data.search(reCat)); //23 |
5) replace 替换字符 利用正则替换
var data = "123123,213,12312,312,3,Cat,cat,dsfsdfs,"; var reCat = /cat/gi; alert(data.replace(reCat,"libinqq")); |
6)split 利用正则分割数组
var data = "123123,213,12312,312,3,Cat,cat,dsfsdfs,"; var reCat = /\,/; var arrdata = data.split(reCat); for (var i = 0; i < arrdata.length; i++) { alert(arrdata[i]); } |
//简单类 var data = "1libinqq,2libinqq,3libinqq,4libinqq"; var reCat = /[123]libinqq/gi; var arrdata = data.match(reCat); for (var i = 0; i < arrdata.length; i++) { alert(arrdata[i]); // 1libinqq 2libinqq 3libinqq } //负向类 var data = "alibinqq,1libinqq,2libinqq,3libinqq,4libinqq"; //\u0062cf var reCat = /[^a123]libinqq/gi; var arrdata = data.match(reCat); for (var i = 0; i < arrdata.length; i++) { alert(arrdata[i]); //4libinqq } //范围类 var data = "libinqq1,libinqq2,libinqq3,libinqq4,libinqq5"; //\u0062cf var reCat = /libinqq[2-3]/gi; var arrdata = data.match(reCat); for (var i = 0; i < arrdata.length; i++) { alert(arrdata[i]); // libinqq2 libinqq3 } //组合类 var data = "a,b,c,w,1,2,3,5"; //\u0062cf var reCat = /[a-q1-4\n]/gi; var arrdata = data.match(reCat); for (var i = 0; i < arrdata.length; i++) { alert(arrdata[i]); // a b c 1 2 3 } |