Not sure why but i can't seem to replace a seemingly simple placeholder.
My approach
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 c开发者_开发问答ontent with a few {PLACEHOLDER} and so on
Any idea why it doesn't work?
Thanks in advance!
Here's something a bit more generic:
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));
};
})();
Usage:
>>> formatString("Hello {name}, {greeting}", {name: "Steve", greeting: "how's it going?"});
"Hello Steve, how's it going?"
JavaScript's string replace does not modify the original string. Also, your code sample only replaces one instance of the string, if you want to replace all, you'll need to append 'g' to the regex.
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
Try this way:
var str="Hello, Venus";
document.write(str.replace("venus", "world"));
精彩评论