简体   繁体   English

在ES6中将字符串转换为模板文字

[英]Converting Strings to Template Literals in ES6

Suppose I have a string like "${a + b}" , say read from JSON, that I'd like interpreted as an ES6 template literal. 假设我有一个类似"${a + b}"的字符串,比如从JSON读取,我想将其解释为ES6模板文字。 I thought something like this might work: 我觉得这样的事情可能有用:

var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);

But this alerts as ${a + b} , so it just does one level of substitution. 但是这个警告为${a + b} ,所以它只进行一级替换。

Tried being clever by interpreting it again: 通过再次解释它试图聪明:

var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);

This still alerts as ${a + b} . 这仍然警告为${a + b}

Tried being even more clever: 试图更聪明:

var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);

This alerts as ${a} + ${b} . 这会以${a} + ${b}提醒。

Starting with a string, eg "${a + b}" , is there any way to have this evaluated to completion as if it were a template literal? 从一个字符串开始,例如"${a + b}" ,是否有任何方法可以将其评估为完成,就像它是模板文字一样? Ideally without eval ! 理想的情况是不eval

Yes, they aren't recursive. 是的,它们不是递归的。

If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. 如果你的起点是一个包含那些占位符的字符串 ,据我所知,没有模板编译器功能。 There's eval , of course; 当然还有eval ; [insert all the usual caveats about using eval — only with content you trust, not if you can avoid it, etc., etc. — here]. [插入关于使用eval所有常见警告 - 仅限于您信任的内容,而不是如果您可以避免它等等 - 这里]。

So for instance: 例如:

 "use strict"; var x = {"add": "${a + b}"}; var a = 10, b = 20; console.log(eval("`" + x.add + "`")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM