变量上的字符串插值 [英] String interpolation on variable
问题描述
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解释器),因为 $ {...}
可以包含任意表达式。
为了完整起见,这里是eval解决方案:
var template = function(tpl,... rest){tpl = tpl.replace(/`/ g,''); //安全预防var t = new Function('return`'+ tpl +'`'); return t(... rest);} var myTpl ='Hello $ {str +!}和$ {other.toUpperCase()}'; console.log(template(myTpl,str ='foo',other = 'bar'));
Say I have a variable str
var str = "123"
Now I could do console.log(`Hello ${str}`)
and it will print Hello 123
Now I have another variable strnew
var strnew = 'Hello ${str}'
Note (based on answers/comments) - strnew
is read from a file, so its always a string and cant be replaced with `
How do I console.log(...)
to print Hello 123
Is it possible wihtout any kind of eval()
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'}));
In a general case, no, not possible without eval (short of writing your own js interpreter), because ${...}
can contain arbitrary expressions.
For completeness' sake, here's the eval solution:
var template = function(tpl, ...rest) {
tpl = tpl.replace(/`/g, ''); // safety precaution
var t = new Function('return `' + tpl + '`');
return t(...rest);
}
var myTpl = 'Hello ${str + "!"} and ${other.toUpperCase()}';
console.log(template(myTpl, str='foo', other='bar'));
这篇关于变量上的字符串插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!