![](/img/trans.png)
[英]Javascript: Replace one or more identical characters with the same number of another character?
[英]Javascript Regex- replace sequence of characters with same number of another character
使用替换功能:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
在$ 2替换之前正在评估length属性,因此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(/(^==)(.+)(==$)/)
表达式的问题
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) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.