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

82
Visualizações
ReplaceAll not replacing all in recursive function

I'm using a recursive function that takes a template string like this:

<div class='${classes}'>

and replaces the template literal placeholder ${classes} with valued from an object that looks like this:

{ classes: 'bg-${color} text-${color}', color: 'blue' }

Something to note here is that within the object, there is more template string nesting, hence the reason for the recursive function.

The thing I cannot work out is why the replace all function is only replacing the 1st instance of ${color}, and leaving the second undefined.

Working snippet below:

function buildTemplate(string) {
  var matched = false;
  string = string.replaceAll(/\$\{(.*?)\}/g, function (match, key) {
    if (match) {
      matched = true;
    }
    const selection = selectors[key];
    delete selectors[key];
    return selection;
  });
  if (matched) {
    string = buildTemplate(string);
  }
  console.log(string);
}

let templateString = "<div class='${classes}'>";
const selectors = { classes: 'bg-${color} text-${color}', color: 'blue' }
buildTemplate(templateString);

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You are deleting selectors, when you need it twice.
Remove line;

// delete selectors[key]

or selection get assigned nothing

No need to delete anything when it's an object that is accessed through a key.

about 4 years ago · Santiago Gelvez 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