replace方法接受两个参数,replace(arg1,arg2);
arg1是要被替换的字符串或者正则表达式
arg2是替换的字符串或者函数。
下面分四种情况来讨论
- arg1是字符串,arg2是字符串
var a='hello,repalce'.replace('hello','Hello') //'Hello,repalce'
- arg1是字符串,arg2是函数
var b='hello,repalce'.replace('repalce',function(match,p1,offset,str){
console.log(match); //replace
console.log(p1); //6
console.log(offset); //hello,replace
console.log(str);//undefined
return match+",javaScript";
})
b //hello,,javaScript
- arg1是正则表达式,arg2是函数
var b='hello,repalce'.replace(/e/gi,function(match,p1,offset,str){
console.log(match);
console.log(p1);
console.log(offset);
console.log(str);
return match+"D";
})
运行结果
b //'heDllo,reDpalceD'
上述根据正则表达式执行了3遍函数。
- arg1是正则表达式,arg2是字符串
var b='hello,repalce'.replace(/e/gi,'DDD');//'hDDDllo,rDDDpalcDDD'
总结:replace如果arg1是正则表达式,arg2是函数,函数会根据正则表达式匹配结果多次执行,函数的返回值作为替换字符串。对于arg2函数。有如下参数:
变量名 | 代表值 |
---|---|
match | 匹配的字符串 |
p1,p2… | 对应arg1为正则表达式中,第n个括号匹配的字符串,前面正则表达式有几个括号表达式,就需要传入几个p形参。例如 /(\a+)(\b+)/,就需要传入两个形参p1,p2来接受 ,p1,p2的值就是对应匹配正则表达式的值,如果匹配,p1,p2为对应匹配值,否则则为undefined |
offset | 字符串偏移量, 字符串从0开始计算,到匹配值所在的位置,例如hello,匹配2,则偏移量是1 |
str | 原字符串 |
对于p1,p2…理解
var str="hello,world,hello";
str.replace(/(he)|(lo)/g,function(match,p1,p2){
console.log(match);
console.log(p1);
console.log(p2);
console.log("======================")
})
从上我们可以看到,对于/(he)|(lo)/g
,正则表达式是he和lo或的关系,只要有一个满足表达式,p1对应he,p2对应lo。如果p1匹配,则p1就是匹配值,否则为undefined。p2同理。
根据以上原理,可以对p1和p2进行判断,来修改字符串的值。
var str="hello,world,hello";
str.replace(/(he)|(lo)/g,function(match,p1,p2){
if(p1) return 'ggg';
if(p2) return 'uuu';
});//'gggluuu,world,gggluuu'