将字符串转换为模板字符串
问题描述:
是否可以像通常的字符串那样创建一个模板字符串
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+'`');