6

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!

2
  • Add ' ' around {PLACEHOLDER} :-) Commented Feb 7, 2011 at 10:54
  • you need to store the result of replace somewhere : try this : var content = 'this is {placeholder}'; content = content.replace(/{placeholder}/,'something'); alert(content); should work Commented Feb 7, 2011 at 11:01

3 Answers 3

17

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?"
Sign up to request clarification or add additional context in comments.

Comments

10

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

Comments

2

Try this way:

var str="Hello, Venus";
document.write(str.replace("venus", "world"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.