我知道在 PHP 中我们可以这样做:
$hello = "foo";
$my_string = "I pity the $hello";
输出:"I pity the foo"
我想知道在 JavaScript 中是否也可以做到这一点。在字符串中使用变量而不使用连接 — 写起来更简洁优雅。
最佳答案
您可以利用 Template Literals并使用以下语法:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
此功能已在 ES2015 (ES6) 中引入。
示例
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
这有多整洁?
奖金:
它还允许在 javascript 中使用多行字符串而无需转义,这对于模板来说非常有用:
return `
<div class="${foo}">
...
</div>
`;
由于旧版浏览器(主要是 Internet Explorer)不支持此语法,您可能需要使用 Babel/Webpack 将您的代码转换为 ES5 以确保它可以在任何地方运行。
旁注:
从 IE8+ 开始,您可以在 console.log
中使用基本的字符串格式:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
关于javascript - 如何在不连接的情况下在 JavaScript 中的字符串中插入变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304014/