Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - 如何在没有连接的情况下插值JavaScript中字符串中的变量?(How to interpolate variables in strings in JavaScript, without concatenation?)

I know in PHP we can do something like this:(我知道在PHP中我们可以做这样的事情:)

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

Output: "I pity the foo"(输出: "I pity the foo")

I was wondering if this same thing is possible in JavaScript as well.(我想知道JavaScript是否也可以实现同样的功能。)

Using variables inside strings without using concatenation — it looks more concise and elegant to write.(在字符串内部使用变量而不使用串联-编写起来看起来更加简洁和优雅。)   ask by DMin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...