考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
试试kiwi吧,它是一个轻量级的JavaScript模块,用于字符串插值。
你可以这样做
Kiwi.compose("I'm % years old!", [age]);
or
Kiwi.compose("I'm %{age} years old!", {"age" : age});
其他回答
你可以使用Prototype的模板系统,如果你真的想用大锤敲开一个坚果:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
扩展Greg Kindel的第二个答案,你可以写一个函数来消除一些样板文件:
var fmt = {
join: function() {
return Array.prototype.slice.call(arguments).join(' ');
},
log: function() {
console.log(this.join(...arguments));
}
}
用法:
var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');
最简单的就是
`my string ${VARIABLE}`
一种效率较低的方法是
function format(str, ...params) {
for(const param of params)
str = str.replace("%", param);
return str;
}
可以和哪个一起使用
format("My % string", "interpolation")
替换更多的ES6版本的@Chris Nielsen的帖子。
String.prototype.supplant = function (o) {
return this.replace(/\${([^\${}]*)}/g,
(a, b) => {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";
string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."
Douglas Crockford的remedy JavaScript包含一个String.prototype.supplant函数。它短小,熟悉,易于使用:
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
如果你不想改变String的原型,你总是可以把它调整成独立的,或者把它放在其他的名称空间里,等等。