2011-02-07 119 views
6

不知道爲什麼,但我似乎無法取代看似簡單的佔位符。JavaScript - 字符串替換

我的做法

var content = 'This is my multi line content with a few {PLACEHOLDER} and so on'; 
content.replace(/{PLACEHOLDER}/, 'something'); 
console.log(content); // This is multi line content with a few {PLACEHOLDER} and so on 

任何想法,爲什麼它不工作?

在此先感謝!

+0

增加 '' 圍繞{}佔位符:-)你需要存儲的地方替換的結果 – 2011-02-07 10:54:40

+0

:試試這個:`var content ='this is {placeholder}'; content = content.replace(/ {placeholder} /,'something');警報(內容); ` 應該工作 – Shrinath 2011-02-07 11:01:56

回答

10

JavaScript的字符串替換不會修改原始字符串。 此外,您的代碼示例僅替換字符串的一個實例,如果要替換所有字符,則需要在正則表達式中附加'g'。

var content = 'This is my multi line content with a few {PLACEHOLDER} and so on'; 
var content2 = content.replace(/{PLACEHOLDER}/g, 'something'); 
console.log(content2); // This is multi line content with a few {PLACEHOLDER} and so on 
+0

謝謝,這正是我需要的! – n00b 2011-02-07 11:02:58

2

試試這個方法:

var str="Hello, Venus"; 
document.write(str.replace("venus", "world")); 
16

這裏有一些更通用的:

var formatString = (function() 
{ 
    var replacer = function(context) 
    { 
     return function(s, name) 
     { 
      return context[name]; 
     }; 
    }; 

    return function(input, context) 
    { 
     return input.replace(/\{(\w+)\}/g, replacer(context)); 
    }; 
})(); 

用法:

>>> formatString("Hello {name}, {greeting}", {name: "Steve", greeting: "how's it going?"}); 
"Hello Steve, how's it going?"