正则方法exec和test,String方法match,replace

来源:互联网 发布:mysql 调用储存过程 编辑:程序博客网 时间:2024/06/06 11:36

test

reg.test(str)

exec

reg.exec(str);

举例:

var reg = /(\w+)@(\w+)\.(\w+)/g;var string = "Please send mail to george@contoso.com and someone@example.com. Thanks!";var result = reg.exec(string);

则result返回

Array[4]    0:  "george@contoso.com"    1:  "george"    2:  "contoso"    3:  "com"    index:  20    input:  "Please send mail to george@contoso.com and someone@example.com. Thanks!"    length:  4

同时测试RegExp.$1返回”george”;

`RegExp.$2`返回`"contoso"`;`RegExp.$3`返回`"com"`;`RegExp.$4`返回`""`;

因为前面的reg中有3个分组,即3个小括号,全局RegExp.$保存的就是匹配到的分组,RegExp.$1-RegExp.$9共9个分组,且只能保存最新的9个分组,

继续执行var result2 = reg.exec(string);
返回

Array[4]    0: "someone@example.com"    1: "someone"    2: "example"    3: "com"    index: 43    input: "Please send mail to george@contoso.com and someone@example.com. Thanks!"    length: 4

因为reg使用g进行全局查找,因此,第二次使用能记住上次查找后的位置。

注意
1. 要让RegExp.$1有值,则必须用var reg = /(\w+)@(\w+).(\w+)/g;这种方式定义正则表达式,不能用new RegExp();

2. 每次执行exec方法,RegExp.$值都会被刷新

match

match是String的方法,返回匹配到的元素

var result3 = string.match(reg);

results:

Array[2]0: "george@contoso.com"1: "someone@example.com"

replace

 var newStr =  str.replace(/[ab\*8]/g,function (ele) {            return '<span style="color:red">'+ele+'</span>';        });

以上是将特殊字符a,b,*,8变为红色。
当回调函数是两个参数时,第二个参数值匹配到的第一组匹配项,即括号中的内容。

'user/add?id=$18&t=update'.replace(/\$(\d+)/g, function (a, b) {            console.log(a);//$18            console.log(b);//18        });

以下是将驼峰命名转换为连字符连接

var hyphenateRE = /([^-])([A-Z])/g;var str = 'BackgroundColorHello';var str1 = str.replace(hyphenateRE, '$1-$2')str1;//"Background-Color-Hello"RegExp.$1;//"r"RegExp.$2;//"H"
阅读全文
0 0