问题描述
我正在尝试用JavaScript中相同数量的虚拟字符替换部分字符串,例如:'== Hello =='with'== ~~~~~ =='。
I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.
此问题已通过和,但我不能让它在JavaScript中工作。我一直在尝试这个:
This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:
txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");
模式匹配工作正常,但替换没有 - 第二部分添加'~~'代替模式匹配的长度。将$ 2放在括号内是行不通的。我该怎么做才能插入正确数量的字符?
The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?
推荐答案
使用替换函数代替:
var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
return $1 + (new Array($2.length + 1).join("~")) + $3;
});
alert(txt);
//-> "==~~~~~=="
这篇关于Javascript正则表达式 - 用相同数量的另一个字符替换字符序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!