如何使用javascript将存储为字符串的模板文字转换回在函数中输出变量的模板文字?

问题描述 投票:0回答:1
const a = "abc";
const tlAsText = "I dont like1 ${a}";
const converted = String.raw`${tlAsText}`;
console.log(converted); // it should output "I dont like1 abc" instead of "I dont like1 ${a}"

代码 Sanbox 进行实验:

https://codesandbox.io/p/sandbox/js-rh338g?file=%2Fsrc%2Findex.mjs

在谷歌和聊天gpt上尝试了很多答案。无济于事。即 eval、String.raw 等

最终目标是我可以将此类模板文字作为字符串存储在数据库中的某个位置,并在以后在任何我想要的地方重用它,只要这些变量在那里。除非有替代方法可以做到这一点。

javascript template-literals
1个回答
0
投票
const a = "abc";
const tlAsText = "I dont like1 ${a}";
const converted = eval("`" + tlAsText + "`");
console.log(converted); // Outputs: I dont like1 abc
© www.soinside.com 2019 - 2024. All rights reserved.