变量上的字符串插值

Faiz Mohamed Haneef:

说我有一个变量 str

var str = "123"

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

现在我有另一个变量 strnew

var strnew = 'Hello ${str}'

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

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

有没有可能 eval()

乔治:

通过简单的操作,${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'}));

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

为了完整起见,这里是评估解决方案:

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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章