Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading