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

107
Visualizações
Multiple replacements within the same variable

I have a string that looks like this:

mylist = `<div>some stuff</div>A lot of code in between<span>more stuff</span>`;

I want to replace some stuff with things and more stuff with many things so I do this:

 mylist = mylist.replace(`some stuff`, 'things');
 mylist = mylist.replace(`more stuff`, 'many things');

It works but I'm sure there must be a much better approach. What should it be?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can chain the replace calls:

mylist = mylist.replace(`some stuff`, 'things').replace(`more stuff`, 'many things');

If you want to store the pairs in an object for scalability, you can loop through the object's entries (with Object.entries) and replace all occurences of each key with its value:

const obj = {
  "some stuff": "things",
  "more stuff": "many things"
}

var str = "<div>some stuff</div>A lot of code in between<span>more stuff</span>"

Object.entries(obj).forEach((k,v) => str = str.replace(k,v))

console.log(str)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can first create a changes object which contain key-value of replace-replacement and then iterate over the key-value and replace the key with the value

This is better because if you have multiple replacements then It will work every time if you just add more replacer - replacement in the object itself.

You don't have to add extra replace statement, just add key-value in the changes and you are good to go.

let mylist = `<div>some stuff</div>A lot of code in between<span>more stuff</span>`;

const changes = {
  "some stuff": "things",
  "more stuff": "many things",
};

mylist = Object.entries(changes).reduce((str, [k, v]) => str.replace(k, v), mylist);
console.log(mylist)

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