Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called Template Literals and use this syntax:(从Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge开始,您可以使用名为Template Literals的ES2015 / ES6功能,并使用以下语法:)
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.(模板文字用反引号(``) (重音)括起来,而不是双引号或单引号。)
Example:(例:)
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?(那有多干净?)
Bonus:(奖金:)
It also allows for multi-line strings in javascript without escaping, which is great for templates:(它还允许在JavaScript中使用多行字符串而不进行转义,这对于模板非常有用:)
return `
<div class="${foo}">
...
</div>
`;
Browser support :(浏览器支持 :)
As this syntax is not supported by older browsers (Internet Explorer and Safari <= 8), you may want to use Babel to transpile your code into ES5 to ensure it will run everywhere.(由于较旧的浏览器(Internet Explorer和Safari <= 8)不支持此语法,因此您可能希望使用Babel将代码转换为ES5,以确保其可在任何地方运行。)
Side note:(边注:)
Starting from IE8+ you can use basic string formatting inside console.log
:(从IE8 +开始,您可以在console.log
使用基本的字符串格式:)
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…