【问题标题】:how to parse javascript nest template literal? [duplicate]如何解析javascript嵌套模板文字? [复制]
【发布时间】:2021-05-19 18:26:36
【问题描述】:
我读了一个文件,内容是“hello ${username}”,我想把它的内容读成模板文字,如何?
let username = "john";
let fileContent = "hello ${username}";
let template= `${fileContent}`;
console.log(template);
【问题讨论】:
标签:
javascript
node.js
templates
deno
【解决方案1】:
您必须自己使用正则表达式和查找图的组合进行替换。
- 正则表达式:
/\$\{(\w+)\}/g
- 查找映射(上下文对象):
{ username: 'john' }
const username = "john";
const fileContent = "hello ${username}";
// We don't need this, we can just use 'fileContent' below
//const template = `${fileContent}`;
const replacer = (template, context) =>
template.replace(/\$\{(\w+)\}/g, (match, key) => context[key]);
console.log(replacer(fileContent, { username }));
【解决方案2】:
我相信eval 就是您要找的。p>
eval() 是全局对象的函数属性,用于评估表示为字符串的 JavaScript 代码。
let username = "john";
let fileContent = "hello ${username}";
let template= `${fileContent}`;
const literal= eval("`" + template + "`");
console.log(literal);