Search code examples
javascriptstr-replacetemplate-literals

Render MULTIPLE Template Literals of Multiple Javascript variables


I have the following code above, which came from this answer:

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 }));

This perfectly works with ONE variable, but not with multiple variables, which is my intention, like:

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

const generatedText = "Hello ${Name}! your Mother ${Mother} is calling you!"; 
const Name = "Ana";
const Mother = "Miley";

console.log(interpolate(generatedText, { Name}, {Mother}));
// Should print: Hello Ana! your Mother Miley is calling you!

Which doesn't work.

I've been thinking about using forEach() but don't know if I could neither how to use in this case. Read about map() but I've only seen this in use to simple replacements like var resultArr = array.map(function(x){return x.replace(REGULAREXPRESSION, newvalue);}); , which is way different of replacing template literals.


Solution

  • Have the second argument you pass to interpolate be a single object with multiple properties. Whenever you want to be able to interpolate something else, add a property to the object (and a ${...} to the generatedText string):

    const interpolate = (str, obj) => str.replace(
      /\${([^}]+)}/g,
      (_, prop) => obj[prop]
    );
    
    const generatedText = "Hello ${Name}! your Mother ${Mother} is calling you!"; 
    const Name = "Ana";
    const Mother = "Miley";
    
    console.log(interpolate(generatedText, { Name, Mother}));
    // Should print: Hello Ana! your Mother Miley is calling you!