Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
How do I resolve a Javascript template literal variable within a string within a variable?

I'm using node.js and experimenting with building a chatbot.

One of my replies is hello ${username} which is being returned in a string from a database query.

msg.channel.send(results.rows[index].reply);

But that just sends hello ${username} when I would like ${username} to resolve to a local variable containing the user's name. e.g. hello Mark.

Is it possible?

Thanks for the replies. I settled on:

let reply = results.rows[index].reply;
reply = reply.replace('${username}', username);

msg.channel.send(reply);

I should have said that I did try:

msg.channel.send(`${results.rows[index].reply}`);

hoping that it would be resolved recursively, but it wasn't.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can replace all occurrences of already declared strings, You can use Map here and declare strings that you are going to replace with.

The below code also handles the case where you didn't declare the replacement string in the map and returns the original string as it is.

const query =
  "hello ${username}, your email id is ${useremail} and password is ${userpassword}";
const map = new Map();
map.set("username", "Mark");
map.set("useremail", "mark@email.com");

const result = query.replace(/\$\{(.*?)\}/g, (...match) => {
  return map.has(match[1]) ? map.get(match[1]) : `${match[0]}`;
});
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

If you know in advance the variables you expect you can do this:

const username = 'John Smith';
const strFromDB = 'hello ${username}.';
const strWithUser = strFromDB.replace('${username}', username);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!