如何在JavaScript中插入变量而没有连接? [英] How to interpolate variables in strings in JavaScript, without concatenation?

查看:116
本文介绍了如何在JavaScript中插入变量而没有连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在PHP中我们可以这样做:

I know in PHP we can do something like this:

$hello = "foo";
$my_string = "I pity the $hello";

输出:我很遗憾foo

我想知道JavaScript中是否也可以这样做。在不使用串联的情况下在字符串中使用变量 - 它看起来更简洁,更优雅。

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.

推荐答案

从Firefox 34 / Chrome开始41 / Safari 9 / Microsoft Edge您可以使用名为模板的ES2015 / ES6功能文字并使用以下语法:

Starting from Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge you can use an ES2015 / ES6 feature called Template Literals and use this syntax:

`String text ${expression}`




模板文字由后退(`(坟墓)包围重音)而不是双引号或单引号。

Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.

示例:

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.

这有多整洁?

奖金:

它还允许javascript中的多行字符串而不会转义,这很棒模板:

It also allows for multi-line strings in javascript without escaping, which is great for templates:

return `
    <div class="${foo}">
         ...
    </div>
`;

浏览器支持

由于旧版浏览器(Internet Explorer和Safari< = 8)不支持此语法,您可能需要使用 Babel 将您的代码转换为ES5,以确保它可以在任何地方运行。

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.

附注:

从IE8 +开始,您可以在 console.log 中使用基本字符串格式:

Starting from IE8+ you can use basic string formatting inside console.log:

console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.

这篇关于如何在JavaScript中插入变量而没有连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆