javascript中replace的高级运用

除了咱们常用的replace()形式正则表达式

stringObject.replace(regexp/substr,replacement)bash

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

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

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

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

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

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

复制代码

下面是实例demo:string

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.在正则表达式中定义了多个捕获组的状况下,传递给函数的参数依次是模式的匹配项,第一个捕获组的匹配项,第二个捕获组的匹配项……,可是,最后两个参数依然是模式的匹配项在字符串中的位置和原始字符串。io

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

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}
复制代码
相关文章
相关标签/搜索