i read a file , content is "hello ${username}", i want to read it's content to template literal, how ?
let username = "john";
let fileContent = "hello ${username}";
let template= `${fileContent}`;
console.log(template);
i read a file , content is "hello ${username}", i want to read it's content to template literal, how ?
let username = "john";
let fileContent = "hello ${username}";
let template= `${fileContent}`;
console.log(template);
You would have to do the replacement yourself using a combination of a regular expression and a lookup map.
/\$\{(\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 }));
I believe that eval
is what your looking for.
The eval()
is a function property of the global object and evaluates JavaScript code represented as a string.
let username = "john";
let fileContent = "hello ${username}";
let template= `${fileContent}`;
const literal= eval("`" + template + "`");
console.log(literal);