考虑下面的代码:

var age = 3;

console.log("I'm " + age + " years old!");

除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?


当前回答

当我不知道如何正确地表达,只想快速地得到一个想法时,我就会在很多语言中使用这种模式:

// 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'));

试试kiwi吧,它是一个轻量级的JavaScript模块,用于字符串插值。

你可以这样做

Kiwi.compose("I'm % years old!", [age]);

or

Kiwi.compose("I'm %{age} years old!", {"age" : age});

试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

Vsprintf接受一个参数数组并返回一个格式化的字符串。

从ES6开始,如果你想在对象键中做字符串插值,你会得到一个SyntaxError: expected属性名,得到'${'如果你做这样的事情:

let age = 3
let obj = { `${age}`: 3 }

你应该做以下事情:

let obj = { [`${age}`]: 3 }

你可以使用Prototype的模板系统,如果你真的想用大锤敲开一个坚果:

var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));