2

如何替换 JavaScript 字符串中的所有 ${...} 实例?例子:

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

变成

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

我尝试遵循Replace multiple strings with multiple other strings中的最佳答案,但您不能拥有以符号开头的键...

非常感谢!

4

1 回答 1

4

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
于 2013-08-27T18:45:16.540 回答