使用一个替换函数:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3")
"$2".length
会将$2
作为字符串字面量,即长度为2的字符串"$2"
。根据MDN文档:
由于我们希望在最终进行替换之前进一步转换匹配结果,所以必须使用函数。
这样可以强制在变换之前进行匹配。
使用内联函数作为参数(和repeat
)-- 这里的$1、$2、$3
是局部变量:
(翻译中如有不妥之处,请多多指教)
txt.replace(/(==)([^=]+)(==)/g, (_,$1,$2,$3) => $1+'~'.repeat($2.length)+$3);
txt = '==Hello==';
//inline function
console.log(
txt.replace(/(==)([^=]+)(==)/g, (_, g1, g2, g3) => g1 + '~'.repeat(g2.length) + g3)
);
在进行$2替换之前,长度属性将被评估,因此replace()无法起作用。 Augustus建议的函数调用应该可以解决问题,另一种方法是使用match()而不是replace()。
使用没有/g的match()会返回一个匹配结果数组,可以像预期的那样连接。
txt="==Hello==";
mat=txt.match(/(==)([^=]+)(==)/); // mat is now ["==Hello==","==","Hello","=="]
txt=mat[1]+Array(mat[2].length+1).join("~")+mat[3]; // txt is now "==~~~~~=="
你从中间表达式中排除了前导/尾随字符,但如果你想要更多的灵活性,你可以使用这个方法来处理由前导/尾随文字括起来的任何内容。
mat=txt.match(/(^==)(.+)(==$)/)
join()
方法生成一个等长的替换字符串。 - Andy E