How can I construct a Template String from a regular string? [duplicate]

强颜欢笑 提交于 2019-11-26 06:43:46

问题


This question already has an answer here:

  • Convert a string to a template string 17 answers

So I have this string:

var name = \"Chaim\";
var templateStr = \"Hello, my name is ${name}\";

How can I convert it into a template-string so that the result would be equal to:

var template = `Hello, my name is ${name}`;

Is there a way to programmatically construct a Template literal?


回答1:


Is there a way to programmatically construct a Template literal?

No. "programmatically" and "literal" are antithetic (except you are in the realms of compilers).

Template strings should better have been named interpolated string literals or so. Please do not confuse them with templates. If you want to use dynamically created strings for templates, use a template engine of your choice.

Of course template literals might help with the implementation of such, and you might get away with something simple as

function assemble(literal, params) {
    return new Function(params, "return `"+literal+"`;"); // TODO: Proper escaping
//             ^^^^^^^^ working in real ES6 environments only, of course
}
var template = assemble("Hello, my name is ${name}", "name");
template("Chaim"); // Hello, my name is Chaim


来源:https://stackoverflow.com/questions/29771597/how-can-i-construct-a-template-string-from-a-regular-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!