[英]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.