变量的字符串插值 [英] String interpolation on variable
问题描述
假设我有一个变量 str
var str = "123"
现在我可以执行 console.log(`Hello ${str}`)
并且它会打印 Hello 123
Now I could do console.log(`Hello ${str}`)
and it will print Hello 123
现在我有另一个变量 strnew
var strnew = 'Hello ${str}'
注意(基于答案/评论) - strnew
是从文件中读取的,因此它始终是一个字符串并且不能用 `
Note (based on answers/comments) - strnew
is read from a file, so its always a string and cant be replaced with `
我如何console.log(...)
打印Hello 123
是否有可能没有任何类型的 eval()
Is it possible wihtout any kind of eval()
推荐答案
使用像 ${str}
这样简单的东西,您可以使用简单的字符串替换:
With something as simple as ${str}
you can use a simple string replacement:
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 解释器),因为 ${...}
可以包含任意表达式.
In a general case, no, not possible without eval (short of writing your own js interpreter), because ${...}
can contain arbitrary expressions.
为了完整起见,这里是 eval 解决方案:
For completeness' sake, here's the eval solution:
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();
这篇关于变量的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!