Search code examples
javascriptecmascript-6template-literals

how to set the template & args in template literals at runtime in JavaScript


I'm fetching template from the db table & the value is returned as

Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}

The values of these are in the req payload

This is how I tried to use the template literals dynamically.

const arg = { customerName: "Ram", websiteLink: "https://www.google.com"}

const template = getMessageTemplateFromDb('customer');

const messageContent = getMessageContent(args, template);

const getMesageContent = (args, template) => {
 const { customerName, websiteLink} = args;
 return `${template}`;
};

I was expecting getMesageContent to return the value as

Hello Ram: Welcome! to our site. This is dummy.Please reach us at https://www.google.com

but that's not the case, I get the value as

Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}

How can I set the template & args at runtime?

Please note, I see some ways to do here https://stackoverflow.com/a/22619256/1326367, however EsLint yells at these.

Thanks!


Solution

  • If you change the Regex of your linked post, you can use that technique.

    const arg = { customerName: "Ram", websiteLink: "https://www.google.com"},
          raw = 'Hello ${customerName}: Welcome! to our site. This is dummy.Please reach us at ${websiteLink}',
          get = (args, template) => template.replace(/\$\{(.*?)\}/g, (match, id) => args[id]);
    
    const replaced = get(arg, raw);
    console.log(replaced)
    
    // Hello Ram: Welcome! to our site. This is dummy.Please reach us at https://www.google.com