Mark Andrew
Mark Andrew

Reputation: 168

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.

Upvotes: 1

Views: 2553

Answers (2)

DecPK
DecPK

Reputation: 25408

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", "[email protected]");

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

Upvotes: 2

Tomer Almog
Tomer Almog

Reputation: 3868

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

Upvotes: 1

Related Questions