考虑下面的代码:

var age = 3;

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

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


当前回答

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开始,如果你想在对象键中做字符串插值,你会得到一个SyntaxError: expected属性名,得到'${'如果你做这样的事情:

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

你应该做以下事情:

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

从ES6开始,你可以使用模板文字:

Const age = 3 console.log(' I'm ${age} years old! ')

附注:注意反引号的使用:' '。

你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。

const age = 3;

console.log(`I'm ${age} years old!`);

http://www.es6fiddle.net/im3c3euc/

最简单的就是

`my string ${VARIABLE}`

一种效率较低的方法是

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

可以和哪个一起使用

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

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

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

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

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