考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
最简单的就是
`my string ${VARIABLE}`
一种效率较低的方法是
function format(str, ...params) {
for(const param of params)
str = str.replace("%", param);
return str;
}
可以和哪个一起使用
format("My % string", "interpolation")
其他回答
找不到我要找的东西,然后找到了
如果你使用的是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内置了这种插值支持。
下面是一个解决方案,它要求您提供一个具有值的对象。如果你不提供一个对象作为参数,它将默认使用全局变量。但是最好还是使用参数,这样更简洁。
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>
在旧的浏览器中使用模板语法会失败,这对于创建供公众使用的HTML很重要。使用连接是乏味且难以阅读的,特别是当您有很多或很长的表达式时,或者如果您必须使用括号来处理数字和字符串项的混合(两者都使用+运算符)。
PHP扩展带引号的字符串,其中包含变量,甚至一些表达式,使用非常紧凑的符号:$a="颜色是$color";
在JavaScript中,可以编写一个有效的函数来支持这一点:var a=S('the color is ',color);,使用可变数量的参数。虽然在本例中没有连接的优势,但当表达式变长时,语法可能会更清晰。或者可以像在PHP中那样,使用JavaScript函数使用美元符号表示表达式的开始。
另一方面,编写一个有效的变通函数来为旧浏览器提供类似模板的字符串展开并不困难。可能已经有人这么做了。
最后,我认为sprintf(就像在C、c++和PHP中一样)可以用JavaScript编写,尽管它的效率要比其他解决方案低一些。
扩展Greg Kindel的第二个答案,你可以写一个函数来消除一些样板文件:
var fmt = {
join: function() {
return Array.prototype.slice.call(arguments).join(' ');
},
log: function() {
console.log(this.join(...arguments));
}
}
用法:
var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');