2013-03-05 19 views
0

我想用替換法替換字符串的一部分,但沒有工作:JavaScript字符串替換不必要的輸出

var string = '<a title="%str%" href="#">%str%</a>', 
    sub = "Strong"; 

    console.log(string.replace(/%str%/,sub)); 

    //result 

    <a title="Strong" href="#">%str%</a> 

似乎只有%STR%的首次出現被替換時,下一次出現忽略/跳過的地方。我在這裏錯過了什麼嗎?

+0

[multiple replace of a letter]的可能重複(http://stackoverflow.com/questions/7466341/multiple-replace-of-a-letter) – 2013-03-05 04:06:48

回答

3

你需要使用「全局」的正則表達式標誌來查找多個ocurrences:

/%str%/g 
2

試試這個,它會做「全球性」取代。

console.log(string.replace(/%str%/g,sub));