简体   繁体   English

如何将字符串转换为模板字符串

[英]How to convert a string to a template string

Let's say I have:假设我有:

 var json = '{"greetings": "`${greetings}`"}';
 var obj = JSON.parse(json);
 var template = obj.greetings; //`${greetings}`

 var greetings = 'hello';

how to evaluate template to get hello?如何评估模板打招呼?

Since JSON.parse() returns obj.greetings as string, you can use eval() to run the string as js.由于JSON.parse()obj.greetings作为字符串返回,因此您可以使用eval()将字符串作为 js 运行。 So just:所以就:

var json = '{"greetings": "`${greetings}`"}';
var obj = JSON.parse(json);
var template = eval(obj.greetings); //`${greetings}`

var greetings = 'hello';
console.log(greetings)// hello

But eval() should always be used with caution as string maybe entered through user input.eval()应始终谨慎使用,因为字符串可能通过用户输入输入。

Edit:编辑:

The above code with eval returns undefined .上面带有eval的代码返回undefined This is because JavaScript Hoisting doesn't work for initialized variable.这是因为 JavaScript 提升不适用于初始化变量。

So we surely need to move the initialisation var greetings = 'hello';所以我们肯定需要移动初始化var greetings = 'hello'; at the top.在顶部。 Solution without eval() :没有eval()解决方案:

Apply template string to the whole string.将模板字符串应用于整个字符串。

 var greetings = 'hello'; var json = `{"greetings": "${greetings}"}`; var obj = JSON.parse(json); var template = obj.greetings; //`${greetings}` console.log(template); //hello

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

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