将字符串转换为模板字符串 [英] Convert a string to a template string

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

问题描述

是否可以像通常的字符串那样创建一个模板字符串

Is it possible to create a template string as a usual string

let a="b:${b}";

然后将其转换为模板字符串

an then convert it into a template string

let b=10;
console.log(a.template());//b:10

没有 eval new Function 和其他动态代码生成方式

without eval, new Function and other means of dynamic code generation?

推荐答案

由于您的模板字符串必须动态地(在运行时)中引用 b 变量,所以答案是:不,没有动态代码生成就不可能。

As your template string must get reference to the b variable dynamicly (in runtime), so the answer is: NO, it impossible to do without dynamic code generation.

但是使用 eval 它很简单:

let tpl = eval('`'+a+'`');

这篇关于将字符串转换为模板字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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