How would you turn a JavaScript variable into a Template literal?

For the general situation, you can use a replacer function to replace every occurrence of ${someProp} with the someProp property on an object:

const interpolate = (str, obj) => str.replace(
  /\${([^}]+)}/g,
  (_, prop) => obj[prop]
);

const generatedText = "But I still need to use it as a template it to get ${variable}.";
const variable = "Successs!!!!";

console.log(interpolate(generatedText, { variable }));

The regular expression \${([^}]+)} means:

  • \$ – Literal $
  • { – Literal {
  • ([^}]+) First (and only) capture group:
    • [^}]+ – One or more characters which are not }
  • } – Literal }

Since prop is the property name found in between the brackets, replace with obj[prop] to replace with the desired replacement.

Leave a Comment