考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
虽然模板可能最适合你描述的情况,但如果你有或想要你的数据和/或参数是可迭代/数组形式,你可以使用String.raw。
String.raw({
raw: ["I'm ", " years old!"]
}, 3);
将数据作为数组,可以使用展开操作符:
const args = [3, 'yesterday'];
String.raw({
raw: ["I'm ", " years old as of ", ""]
}, ...args);
其他回答
当我不知道如何正确地表达,只想快速地得到一个想法时,我就会在很多语言中使用这种模式:
// JavaScript
let stringValue = 'Hello, my name is {name}. You {action} my {relation}.'
.replace(/{name}/g ,'Inigo Montoya')
.replace(/{action}/g ,'killed')
.replace(/{relation}/g,'father')
;
虽然不是特别高效,但我觉得它可读。它总是有效的,而且总是可用的:
' VBScript
dim template = "Hello, my name is {name}. You {action} my {relation}."
dim stringvalue = template
stringValue = replace(stringvalue, "{name}" ,"Luke Skywalker")
stringValue = replace(stringvalue, "{relation}","Father")
stringValue = replace(stringvalue, "{action}" ,"are")
总是
* COBOL
INSPECT stringvalue REPLACING FIRST '{name}' BY 'Grendel Mother'
INSPECT stringvalue REPLACING FIRST '{relation}' BY 'Son shoulder'
INSPECT stringvalue REPLACING FIRST '{action}' BY 'made a gaping mortal-making wound upon.'
我可以给你们举个例子:
函数fullName(first, last) { let fullName = first + " " + last; 返回fullName; } 函数fullNameStringInterpolation(first, last) { let fullName = ' ${first} ${last} '; 返回fullName; } console.log('Old School: ' + fullName('Carlos', 'Gutierrez')); console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));
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的原型,你总是可以把它调整成独立的,或者把它放在其他的名称空间里,等等。
你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。
const age = 3;
console.log(`I'm ${age} years old!`);
http://www.es6fiddle.net/im3c3euc/
警告:避免任何不允许您转义其自己的分隔符的模板系统。例如,使用此处提到的supplant()方法将无法输出以下内容。
“多亏了我的年龄变量,我才3岁。”
简单的插值可能适用于小型的自包含脚本,但通常会出现这种设计缺陷,限制任何重要的使用。老实说,我更喜欢DOM模板,比如:
<div> I am <span id="age"></span> years old!</div>
$('#age').text(3)
另外,如果你只是厌倦了字符串连接,总有替代语法:
var age = 3;
var str = ["I'm only", age, "years old"].join(" ");