在ES6中将字符串转换为模板文字 [英] Converting Strings to Template Literals in ES6
问题描述
假设我有一个字符串,如$ {a + b}
,比如从JSON读取,我想将其解释为ES6模板文字。我认为这样的事情可能有用:
Suppose I have a string like "${a + b}"
, say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:
var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);
但此警报为 $ {a + b}
,所以它只做一个替换级别。
But this alerts as ${a + b}
, so it just does one level of substitution.
通过再次解释它试图变得聪明:
Tried being clever by interpreting it again:
var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);
这仍然以 $ {a + b} $ c $警告c>。
尝试更聪明:
var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);
此提醒 $ {a} + $ {b}
。
以字符串开头,例如$ {a + b}
,有没有办法让这个评估完成,好像它是模板文字一样?理想情况下没有 eval
!
Starting with a string, e.g. "${a + b}"
, is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval
!
推荐答案
是的,它们不是递归的。
Yes, they aren't recursive.
如果您的起点是包含这些占位符的字符串,据我所知,没有模板编译器功能。当然有 eval
; [插入关于使用 eval
的所有常见警告 —只有你信任的内容,而不是你可以避免它等等。 —这里]。
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; [insert all the usual caveats about using eval
— only with content you trust, not if you can avoid it, etc., etc. — here].
例如:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));
这篇关于在ES6中将字符串转换为模板文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!