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!
asked Feb 7, 2011 at 10:49
n00b
16.7k21 gold badges59 silver badges72 bronze badges
3 Answers 3
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?"
answered Feb 7, 2011 at 11:10
Jonny Buchanan
62.9k17 gold badges147 silver badges150 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
answered Feb 7, 2011 at 10:55
typo.pl
8,9302 gold badges31 silver badges29 bronze badges
Comments
Try this way:
var str="Hello, Venus";
document.write(str.replace("venus", "world"));
answered Feb 7, 2011 at 10:53
user517400
Comments
lang-js
var content = 'this is {placeholder}'; content = content.replace(/{placeholder}/,'something'); alert(content);should work