Reputation: 16566
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 content with a few {PLACEHOLDER} and so on
Any idea why it doesn't work?
Thanks in advance!
Upvotes: 6
Views: 6589
Reputation: 62813
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?"
Upvotes: 17
Reputation: 8942
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
Upvotes: 10
Reputation:
Try this way:
var str="Hello, Venus";
document.write(str.replace("venus", "world"));
Upvotes: 2