javascript - 字符串替换

n00*_*00b 6 javascript regex

不知道为什么,但我似乎无法取代看似简单的占位符.

我的方法

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
Run Code Online (Sandbox Code Playgroud)

知道为什么它不起作用吗?

提前致谢!

Jon*_*nan 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));
    };
})();
Run Code Online (Sandbox Code Playgroud)

用法:

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


typ*_*.pl 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
Run Code Online (Sandbox Code Playgroud)