我需要用动态值替换html字符串。此动态值(HTML编码)是替换html字符串中的模式。
var htmlstring = "<div>{NAME}</div>";
var name = "$<Anonymous>" //Encoded form of "$<Anonymous>";
html = htmlstring.replace(/{NAME}/g,name);
Run Code Online (Sandbox Code Playgroud)
我需要得到 “ $ <Anonymous>”作为输出,但我得到“ {NAME} lt; Anonymous>”作为输出。这是因为“ $&”匹配整个匹配项“ {NAME}”,并将“ $&”替换为“{名称}”。
谁能建议我如何用JavaScript做到这一点?
从 Docs of replace,$&插入匹配的子字符串。
您可以使用替换回调来获取$&替换字符串中的文字。
var htmlstring = "<div>{NAME}</div>";
var name = "$<Anonymous>" //Encoded form of "$<Annonymous>";
var html = htmlstring.replace(/{NAME}/g, function(m) {
return name;
});
console.log(html);
document.write(html);Run Code Online (Sandbox Code Playgroud)
在JavaScript中,替换为 $,您需要用另一个美元符号对美元符号进行转义,否则,将$&被视为对整个匹配值的反向引用(即{NAME}此处)。
您需要使用
var name = "$$<Anonymous>"
^^
Run Code Online (Sandbox Code Playgroud)
var name = "$$<Anonymous>"
^^
Run Code Online (Sandbox Code Playgroud)
模式插入
$$插入“ $”。
$&插入匹配的子字符串。
| 归档时间: |
|
| 查看次数: |
1591 次 |
| 最近记录: |