Javascript正则表达式-用相同数量的另一个字符替换字符序列
我试图用 JavaScript 中相同数量的虚拟字符替换字符串的一部分,例如:'==Hello==' 替换为 '==~~~~~~=='。
这个问题已使用 Perl< /a> 和 PHP,但我无法让它在 JavaScript 中工作。我一直在尝试这样做:
txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");
模式匹配工作正常,但替换不行 - 第二部分添加“~~”而不是模式匹配的长度。将“$2”放在括号内不起作用。我该怎么做才能让它插入正确数量的字符?
I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.
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");
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用函数进行替换:
Use a function for replacement instead:
该表达式的问题
在于
"$2".length
强制将$2
视为字符串文字,即字符串"$2"
,长度为 2。从 MDN 文档:
这迫使在转换之前评估比赛。
使用内联函数作为参数(和
重复
) - 这里$1, $2, $3
是局部变量:The issue with the expression
is that
"$2".length
forces$2
to be taken as a string literal, namely the string"$2"
, that has length 2.From the MDN docs:
This forces evaluation of the match before the transformation.
With an inline function as parameter (and
repeat
) -- here$1, $2, $3
are local variables:长度属性在 $2 替换之前被评估,因此 Replace() 将不起作用。 Augustus 建议的函数调用应该可以工作,另一种方法是使用 match() 而不是 Replace()。
使用不带 /g 的 match() 会返回一个匹配结果数组,可以按照您的预期进行连接。
您从中间表达式中排除了前导/尾随字符,但如果您想要更大的灵活性,您可以使用它并处理由前导/尾随文字括起来的任何内容。
The length attribute is being evaluated before the $2 substitution so replace() won't work. The function call suggested by Augustus should work, another approach would be using match() instead of replace().
Using match() without the /g, returns an array of match results which can be joined as you expect.
You excluded the leading/trailing character from the middle expression, but if you want more flexibility you could use this and handle anything bracketed by the leading/trailing literals.
工作示例使用以下片段:
代码中的问题是您总是测量 < 的长度code>"$2" (始终是包含两个字符的字符串)。通过该功能,您可以测量匹配零件的长度。有关更多示例,请参阅有关替换的文档。
A working sample uses the following fragment:
The problem in your code was that you always measured the length of
"$2"
(always a string with two characters). By having the function you can measure the length of the matched part. See the documentation on replace for further examples.