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

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

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 Denunciar

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