考虑下面的代码:

var age = 3;

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

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


当前回答

找不到我要找的东西,然后找到了

如果你使用的是Node.js,有一个内置的utipackage,它有一个format函数,工作方式是这样的:

util.format("Hello my name is %s", "Brent");
> Hello my name is Brent

巧合的是,在Node.js -中,这也被内置到console.log版本中

console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError

其他回答

虽然模板可能最适合你描述的情况,但如果你有或想要你的数据和/或参数是可迭代/数组形式,你可以使用String.raw。

String.raw({
  raw: ["I'm ", " years old!"]
}, 3);

将数据作为数组,可以使用展开操作符:

const args = [3, 'yesterday'];
String.raw({
  raw: ["I'm ", " years old as of ", ""]
}, ...args);

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

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

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

最简单的就是

`my string ${VARIABLE}`

一种效率较低的方法是

function format(str, ...params) {
  for(const param of params)
    str = str.replace("%", param);
   return str;
}

可以和哪个一起使用

format("My % string", "interpolation")

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

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

你应该做以下事情:

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

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

你可以这样做

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

or

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