kehphin
kehphin

Reputation: 159

Replacing ${...} in javascript string?

How do you replace all instances of ${...} in a javascript string? Example:

var before = "My name is ${name} and I like ${sport} because ${sport} is challenging."

becomes

var after = "My name is Bob and I like soccer because soccer is challenging."

I tried following the best answer from Replace multiple strings with multiple other strings, but you cannot have a key that starts with a symbol...

Many thanks!

Upvotes: 2

Views: 110

Answers (1)

Martin Ender
Martin Ender

Reputation: 44259

Modifying the answer from the question you linked, you can capture part of the match (only the name) and use that as the key:

var str = "My name is ${name} and I like ${sport} because ${sport} is challenging.";
var mapObj = {
   name:"Bob",
   sport:"soccer"
};
str = str.replace(/[$]{([^{}]+)}/g, function(match, key){
  return mapObj[key];
});

The second argument to the anonymous function will be filled with what was matched inside the first pair of parentheses in the pattern (i.e. what was matched by [^{}]*).

Of course, you should add some sanity check that your key is actually present in the map. Alternatively, use the approach from the other question and just list the allowed names in the pattern:

/[$]{(name|sport)}/g

Upvotes: 4

Related Questions