Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda