Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda