The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.
However,如果你只需要做字符串插值,你可以使用:
const str = `My name is ${replacements.name} and my age is ${replacements.age}.`
Note the backticks delimiting the string, they are required.
For an answer suiting the particular OP's requirement, you could use String.prototype.replace()
for the replacements.
The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).
var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
str = 'My Name is %NAME% and my age is %AGE%.';
str = str.replace(/%\w+%/g, function(all) {
return replacements[all] || all;
});
jsFiddle.
如果某些替换项不是字符串,请确保它们首先存在于对象中.如果您有类似示例的格式,即用百分号括起来,则可以使用in
运算符来实现这一点.
jsFiddle.
但是,如果您的格式没有特殊的格式,即任何字符串,并且您的replacements对象没有null
原型,请使用Object.prototype.hasOwnProperty()
,除非您可以保证任何可能替换的子字符串都不会与原型上的属性名称冲突.
jsFiddle.
Otherwise, if your replacement string was 'hasOwnProperty'
, you would get a resultant messed up string.
jsFiddle
As a side note, you should be called replacements
an Object
, not an Array
.