变量上的字符串插值 [英] String interpolation on variable

查看:111
本文介绍了变量上的字符串插值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个变量 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆