1

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);
user1575761
  • 466
  • 1
  • 6
  • 9

2 Answers2

0

You would have to do the replacement yourself using a combination of a regular expression and a lookup map.

  1. Regex: /\$\{(\w+)\}/g
  2. Lookup-map (context object): { 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 }));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

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);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53