test
reg.test(str)
exec
reg.exec(str);
@H_404_13@举例:
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);
@H_404_13@则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
@H_404_13@同时测试RegExp.$1
返回”george”;
`RegExp.$2`返回`"contoso"`; `RegExp.$3`返回`"com"`; `RegExp.$4`返回`""`;
@H_404_13@因为前面的reg中有3个分组,即3个小括号,全局@H_404_13@继续执行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
@H_404_13@因为reg
使用g进行全局查找,因此,第二次使用能记住上次查找后的位置。
@H_404_13@注意: 1. 要让RegExp.$1有值,则必须用var reg = /(\w+)@(\w+).(\w+)/g;这种方式定义正则表达式,不能用new RegExp(); @H_404_13@2. 每次执行exec方法,RegExp.$值都会被刷新
match
@H_404_13@match是String的方法,返回匹配到的元素var result3 = string.match(reg);
@H_404_13@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>';
});
@H_404_13@以上是将特殊字符a,b,*,8变为红色。 当回调函数是两个参数时,第二个参数值匹配到的第一组匹配项,即括号中的内容。
'user/add?id=$18&t=update'.replace(/\$(\d+)/g,function (a,b) {
console.log(a);//$18
console.log(b);//18
});
@H_404_13@以下是将驼峰命名转换为连字符连接
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"