考虑下面的代码:

var age = 3;

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

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


当前回答

下面是一个解决方案,它要求您提供一个具有值的对象。如果你不提供一个对象作为参数,它将默认使用全局变量。但是最好还是使用参数,这样更简洁。

String.prototype.interpolate = function(props) { return this.replace(/\{(\w+)\}/g, function(match, expr) { return (props || window)[expr]; }); }; // Test: // Using the parameter (advised approach) document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 }); // Using the global scope var eruption2 = 116; document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate(); <div id="resultA"></div><div id="resultB"></div>

其他回答

下面是一个解决方案,它要求您提供一个具有值的对象。如果你不提供一个对象作为参数,它将默认使用全局变量。但是最好还是使用参数,这样更简洁。

String.prototype.interpolate = function(props) { return this.replace(/\{(\w+)\}/g, function(match, expr) { return (props || window)[expr]; }); }; // Test: // Using the parameter (advised approach) document.getElementById("resultA").innerText = "Eruption 1: {eruption1}".interpolate({ eruption1: 112 }); // Using the global scope var eruption2 = 116; document.getElementById("resultB").innerText = "Eruption 2: {eruption2}".interpolate(); <div id="resultA"></div><div id="resultB"></div>

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

如果你使用的是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

如果您想在console.log输出中插入,那么只需

console.log("Eruption 1: %s", eruption1);
                         ^^

这里,%s是所谓的“格式说明符”。log内置了这种插值支持。

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

const age = 3;

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

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

我可以给你们举个例子:

函数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'));