string中的JavaScriptvariables不需要连接 – 就像PHP一样
我知道在PHP中,我们可以做这样的事情:
$hello = "foo"; $my_string = "I pity the $hello"; 输出:“我可怜foo”
我想知道在JavaScript中是否也可以做到这一点。 在不使用串联的情况下在string中使用variables – 它看起来更简洁和优雅。
从Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge开始,您可以使用名为“ 模板文字”的ES2015 / ES6function,并使用以下语法:
 `String text ${expression}` 
模板文字由反勾号(“) (粗体重音)而不是双引号或单引号括起来。
例:
 var a = 5; var b = 10; console.log(`Fifteen is ${a + b}.`); // "Fifteen is 15. 
那是多么的整洁?
奖金:
它也允许在javascript中的多行string,而不逃脱,这是模板的好主意:
 return ` <div class="${foo}"> ... </div> `; 
浏览器支持 :
由于旧版浏览器(Internet Explorer和Safari <= 8)不支持此语法,因此您可能希望使用Babel将您的代码转换为ES5,以确保它可以在任何地方运行。
边注:
 从IE8 +开始,你可以在console.log使用基本的string格式: 
 console.log('%s is %d.', 'Fifteen', 15); // Fifteen is 15. 
在 Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,不可能在javascript中使用。 你将不得不诉诸于:
 var hello = "foo"; var my_string = "I pity the " + hello; 
在 Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,没有。 虽然你可以尝试sprintf的JavaScript来得到一半:
 var hello = "foo"; var my_string = sprintf("I pity the %s", hello); 
你可以做到这一点,但不是特别的一般
 'I pity the $fool'.replace('$fool', 'fool') 
如果你真的需要的话,你可以很容易地写出一个能够智能化的function
如果你喜欢写CoffeeScript,你可以这样做:
 hello = "foo" my_string = "I pity the #{hello}" 
CoffeeScript实际上是JavaScript,但语法更好。
有关CoffeeScript的概述,请查看本初学者指南 。
完整的答案,准备使用:
  var Strings = { create : (function() { var regexp = /{([^{]+)}/g; return function(str, o) { return str.replace(regexp, function(ignore, key){ return (key = o[key]) == null ? '' : key; }); } })() }; 
作为
 Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'}); 
将其附加到String.prototype:
 String.prototype.create = function(o) { return Strings.create(this, o); } 
然后用作:
 "My firstname is ${first}".create({first:'Neo'}); 
如果您正在尝试为微模板进行插值,我喜欢Mustache.js 。
你可以使用这个javascript函数来做这种模板。 不需要包含整个库。
 function createStringFromTemplate(template, variables) { return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){ return variables[varName]; }); } createStringFromTemplate( "I would like to receive email updates from {list_name} {var1} {var2} {var3}.", { list_name : "this store", var1 : "FOO", var2 : "BAR", var3 : "BAZ" } ); 
  输出 : "I would like to receive email updates from this store FOO BAR BAZ." 
使用函数作为String.replace()函数的参数是ECMAScript v3规范的一部分。 看到这个回答更多的细节。
我写了这个npm包的stringinject https://www.npmjs.com/package/stringinject它允许你做以下;
 var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]); 
这将用数组项replace{0}和{1},并返回以下string
 "this is a test string for stringInject" 
或者你可以用对象键和值replace占位符,如下所示:
 var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" }); "My username is tjcafferkey on Github" 
 那么,你可以使用this is ${variable}或者你可以使用"this is "+variable这两个工作都很好。 
 还要记得在this is ${variable}而不是“or”周围使用tilda(“)