考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
在旧的浏览器中使用模板语法会失败,这对于创建供公众使用的HTML很重要。使用连接是乏味且难以阅读的,特别是当您有很多或很长的表达式时,或者如果您必须使用括号来处理数字和字符串项的混合(两者都使用+运算符)。
PHP扩展带引号的字符串,其中包含变量,甚至一些表达式,使用非常紧凑的符号:$a="颜色是$color";
在JavaScript中,可以编写一个有效的函数来支持这一点:var a=S('the color is ',color);,使用可变数量的参数。虽然在本例中没有连接的优势,但当表达式变长时,语法可能会更清晰。或者可以像在PHP中那样,使用JavaScript函数使用美元符号表示表达式的开始。
另一方面,编写一个有效的变通函数来为旧浏览器提供类似模板的字符串展开并不困难。可能已经有人这么做了。
最后,我认为sprintf(就像在C、c++和PHP中一样)可以用JavaScript编写,尽管它的效率要比其他解决方案低一些。
其他回答
替换更多的ES6版本的@Chris Nielsen的帖子。
String.prototype.supplant = function (o) {
return this.replace(/\${([^\${}]*)}/g,
(a, b) => {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";
string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."
当我不知道如何正确地表达,只想快速地得到一个想法时,我就会在很多语言中使用这种模式:
// 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.'
你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。
const age = 3;
console.log(`I'm ${age} years old!`);
http://www.es6fiddle.net/im3c3euc/
找不到我要找的东西,然后找到了
如果你使用的是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
从ES6开始,你可以使用模板文字:
Const age = 3 console.log(' I'm ${age} years old! ')
附注:注意反引号的使用:' '。