如何从常规字符串构造模板字符串? [英] How can I construct a Template String from a regular string?

查看:149
本文介绍了如何从常规字符串构造模板字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个字符串

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

如何将其转换为模板字符串,以便结果等于: p>

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?

推荐答案


有没有办法以编程方式构建一个模板文字?

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

这篇关于如何从常规字符串构造模板字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆