replace的高级运用

xiaoxiao2021-02-28  43

除了我们经常使用的replace()形式

stringObject.replace(regexp/substr,replacement),

replace方法的第二个参数也可以是一个函数,形如:

stringObject.replace(regexp/substr,function(){});

这个函数应该有个return值,表示应该被替换的匹配项。

下面会根据正则的匹配项和捕获组,分2种情况,总结第二个参数function的具体用法。

情况1.当只有一个匹配项的(即与模式匹配的字符串)情况下,会向该函数传递三个参数:模式的匹配项,模式匹配项在字符串中的位置和原始字符串,形如:

stringObject.replace( regexp/substr, function(match,pos,originalText){} );

下面是实例demo:

var str = "{a},{b}"; str.replace(/\{\w+\}/g,function(match,pos,original){ console.log(match); console.log(pos); console.log(original) }) 输出结果是: {a} 0 {a},{b} {b} 4 {a},{b}

情况2.在正则表达式中定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项,第一个捕获组的匹配项,第二个捕获组的匹配项……,但是,最后两个参数依然是模式的匹配项在字符串中的位置和原始字符串。

下面是根据上面的demo进行稍加修改,

var str = "{a},{b}"; str.replace(/\{(\w+)\}/g,function(match,capture,pos,original){ console.log(match); console.log(capture); console.log(pos); console.log(original) }) 输出结果是: {a} a 0 {a},{b} {b} b 4 {a},{b}
转载请注明原文地址: https://www.6miu.com/read-2621495.html

最新回复(0)