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