变量的字符串插值

Fai*_*eef 21 javascript ecmascript-6

说我有一个变量 str

var str = "123"
Run Code Online (Sandbox Code Playgroud)

现在我可以做console.log(`Hello ${str}`),它会打印出来Hello 123

现在我有另一个变量 strnew

var strnew = 'Hello ${str}'
Run Code Online (Sandbox Code Playgroud)

注意(基于答案/评论) - strnew从文件中读取,因此它总是一个字符串,不能替换为`

我该如何console.log(...)打印Hello 123

有可能没有任何一种 eval()

geo*_*org 23

有了简单的东西就${str}可以使用简单的字符串替换:

var template = (tpl, args) => tpl.replace(/\${(\w+)}/g, (_, v) => args[v]);

var tpl = 'Hello ${str} and ${other}';

console.log(template(tpl, {str: 'foo', other: 'bar'}));
Run Code Online (Sandbox Code Playgroud)

在一般情况下,不,没有eval(没有编写自己的js解释器),因为${...}可以包含任意表达式.

为了完整起见,这是eval解决方案:

var template = function(tpl, args) {
    var keys = Object.keys(args),
        fn = new Function(...keys, 
          'return `' + tpl.replace(/`/g, '\\`') + '`');
    return fn(...keys.map(x => args[x]));
};


function test() {
    var myTpl = 'Hello ${str + "!"} and ${other.toUpperCase()}';
    console.log(template(myTpl, {str: 'foo', other: 'bar'}));
}

test();
Run Code Online (Sandbox Code Playgroud)