2015-12-02 120 views
3

我需要用動態值替換一個html字符串。這個動態值(HTML編碼)是要替換html字符串中的一個模式。

var htmlstring = "<div>{NAME}</div>"; 
var name = "$&lt;Anonymous&gt;" //Encoded form of "$<Anonymous>"; 
html = htmlstring.replace(/{NAME}/g,name); 

我需要得到「$ <匿名>」作爲輸出,但我得到「{NAME} LT;匿名>」作爲output.This是因爲 「$ &」 整場比賽「相匹配{NAME}「,並將」$ &「替換爲」{NAME}「。

任何人都可以提出如何在JavaScript中實現這一點?

+0

請考慮接受第一個提供正確答案(見[如何接受SO答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-的回答工作))。 –

回答

4

在JavaScript中,與$更換,你需要逃避與另一美元符號的美元符號,否則,$&被視爲反向引用整個匹配的值(即{NAME}這裏)。

您需要使用

var name = "$$&lt;Anonymous&gt;" 
      ^^ 

var htmlstring = "<div>{NAME}</div>"; 
 
var name = "$$&lt;Anonymous&gt;" //Encoded form of "$<Annonymous>"; 
 
html = htmlstring.replace(/{NAME}/g,name); 
 
document.write(html);

String#replace reference

模式插入
$$                  插入「$」。
$&                插入匹配的子串。

3

來自Docs of replace$&插入匹配的子字符串。

enter image description here

可以使用替代回調以獲取$&文字被替換的字符串中。

var htmlstring = "<div>{NAME}</div>"; 
 
var name = "$&lt;Anonymous&gt;" //Encoded form of "$<Annonymous>"; 
 
var html = htmlstring.replace(/{NAME}/g, function(m) { 
 
    return name; 
 
}); 
 

 
console.log(html); 
 
document.write(html);