不确定为什么,但我似乎无法取代看似简单的占位符。
我的方法
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 :(得分:17)
这里有点更通用的东西:
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?"
答案 1 :(得分:10)
JavaScript的字符串替换不会修改原始字符串。 此外,您的代码示例仅替换字符串的一个实例,如果要替换all,则需要将'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
答案 2 :(得分:2)
尝试这种方式:
var str="Hello, Venus";
document.write(str.replace("venus", "world"));