2016-12-03 27 views
0
var abc = "text"; 
var text = "content of text"; 
var out_right = ` ${abc}=${text}`; // get string "text=content_of_text" 

var out_template = '${abc}=${text}'; 
var out_wrong_0 = ` out_template `; 
var out_wrong_1 = ` ${out_template} `; 

我的问题是如何使用字符串out_template得到我需要的字符串:"text=content_of_text"路线插值使用反引号与现有的字符串模板

回答

2

反引用文字是编译时的东西,没有运行时设施来重新评估它们。这意味着,你要么不得不求助于eval,如

var abc = "text"; 
 
var text = "content of text"; 
 
var out_template = '${abc}=${text}'; 
 
console.log(eval("`" + out_template + "`"));

,或者使用其他模板技术(util.format,胡子等)。

+0

greate答案,也告诉为什么!非常感谢。 – tlqtangok