本帖最后由 laughing 于 2013-1-11 06:03 编辑
javascript正则表达式的基本知识
1 javascript 正则对象创建 和用法
声明javascript 正则表达式
var reCat = new RegExp("cat");
你也可以
var reCat = /cat/; //Perl 风格 (推荐)
2 学习最常用的 test exec match search replace split 6个方法
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); //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);
}
|