Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - string replace

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!

like image 399
n00b Avatar asked Feb 07 '11 10:02

n00b


People also ask

What is string replace in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.

Can you change strings in JavaScript?

Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character. in fact every occurence of the same string is ONE object.

How do you replace words in JavaScript?

To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.


1 Answers

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?"
like image 102
Jonny Buchanan Avatar answered Oct 13 '22 00:10

Jonny Buchanan