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

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

输出:"I pity the foo"

我想知道同样的事情在JavaScript中是否也是可能的。在字符串中使用变量而不使用连接-它看起来更简洁和优雅。


当前回答

在Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge之前,没有。尽管你可以尝试JavaScript的sprintf来实现:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);

其他回答

如果你想为微模板做插值,我喜欢用Mustache.js。

你可以利用模板字面量并使用以下语法:

`String text ${expression}`

模板字面量由后撇号(' ')(严肃重音)括起来,而不是双引号或单引号。

该特性已在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.

如果你喜欢写CoffeeScript,你可以这样做:

hello = "foo"
my_string = "I pity the #{hello}"

CoffeeScript实际上是javascript,但是语法更好。

要了解CoffeeScript的概述,请查看初学者指南。

我会使用反撇号' '。

let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'

但如果在创建msg1时不知道name1。

例如,如果msg1来自API。

你可以使用:

let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'

const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
    return eval(key);
});
console.log(result); // 'Hello Geoffrey'

它将用他的值替换${name2}。

String.prototype.interpole = function () {
    var c=0, txt=this;
    while (txt.search(/{var}/g) > 0){
        txt = txt.replace(/{var}/, arguments[c]);
        c++;
    }
    return txt;
}

Uso:

var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"