2013-08-27 42 views
2

如何在JavaScript字符串中替換$ {...}的所有實例?例如:

var before = "My name is ${name} and I like ${sport} because ${sport} is challenging." 

成爲

var after = "My name is Bob and I like soccer because soccer is challenging." 

我試圖從Replace multiple strings with multiple other strings以下最好的答案,但你不能有一個帶有符號開始的關鍵...

非常感謝!

+1

您嘗試過什麼嗎? – Blender

回答

4

修改從您鏈接的問題的答案,你可以在比賽(只有名稱)的capture一部分,並用其作爲重點:

var str = "My name is ${name} and I like ${sport} because ${sport} is challenging."; 
var mapObj = { 
    name:"Bob", 
    sport:"soccer" 
}; 
str = str.replace(/[$]{([^{}]+)}/g, function(match, key){ 
    return mapObj[key]; 
}); 

匿名函數的第二個參數將被填充在模式中第一對括號內匹配的內容(即與[^{}]*相匹配的內容)。

當然,你應該添加一些理智檢查,你的key實際上是在地圖上。或者,使用另一個問題中的方法,只列出模式中允許的名稱:

/[$]{(name|sport)}/g 
+1

這是邪惡的天才。 – PlantTheIdea

+0

我真的需要刷一下我的正則表達式,謝謝你快速簡潔的回答! – kehphin

+0

@ user1464011我鏈接的教程是一個很好的開始點;) –