替换包含$&的字符串在JavaScript正则表达式 [英] Replace string containing $& in JavaScript regex
问题描述
我需要用动态值替换html字符串。这个动态值(HTML编码)是替换html字符串中的模式。
I need to replace a html string with a dynamic value.This dynamic value(HTML encode) is to replace a pattern in the html string.
var htmlstring = "<div>{NAME}</div>";
var name = "$<Anonymous>" //Encoded form of "$<Anonymous>";
html = htmlstring.replace(/{NAME}/g,name);
我需要$< Anonymous>作为输出但是我得{NAME} lt;匿名>作为输出。这是因为$&匹配整个匹配{NAME}并替换$&使用{NAME}。
I need to get "$<Anonymous>" as output but i get "{NAME}lt;Anonymous>" as output.This is because "$&" matches the whole match "{NAME}" and replace "$&" with "{NAME}".
任何人都可以建议我如何在JavaScript中实现这一点?
Can anyone suggest how can I achieve this in JavaScript?
推荐答案
在JavaScript中,要替换为 $
,您需要使用另一个美元符号转义美元符号,否则, $ &
被视为对整个匹配值的反向引用(即 {NAME}
此处)。
In JavaScript, to replace with $
, you need to escape the dollar symbol with another dollar symbol, otherwise, $&
is treated as a backreference to the whole matched value (i.e. {NAME}
here).
您需要使用
var name = "$$<Anonymous>"
^^
var htmlstring = "<div>{NAME}</div>";
var name = "$$<Anonymous>" //Encoded form of "$<Annonymous>";
html = htmlstring.replace(/{NAME}/g,name);
document.write(html);
See String#replace
reference:
模式插入
$$
; 插入$。
$&
插入匹配的子字符串。
Pattern Inserts
$$
Inserts a "$".
$&
Inserts the matched substring.
这篇关于替换包含$&的字符串在JavaScript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!