正则方法exec和test,String方法match,replace
发布时间:2020-12-14 00:36:05 所属栏目:百科 来源:网络整理
导读: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 : "georg
testreg.test(str)
execreg.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.$2`返回`"contoso"`; `RegExp.$3`返回`"com"`; `RegExp.$4`返回`""`;
继续执行 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
因为 注意: 2. 每次执行exec方法,RegExp.$值都会被刷新 matchmatch是String的方法,返回匹配到的元素 var result3 = string.match(reg);
results: Array[2]
0: "george@contoso.com"
1: "someone@example.com"
replacevar 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"
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |