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

174
Vistas
JavaScript: match a word in a text with a word in array and replace it

I need to change this text:

var text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot`;

using these 2 arrays :

var arrOld = ["coffee", "apple", "banana" , "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];

to get result like this:

`this is an example text. 1laptop , 2 laptop , 1 keyboard, 2keyboard , ?mouse ,printer`

I was trying something like:

for (let i = 0; i < arrOld.length; i++) {
arrNew[i];
arrOld[i];
text.replace(arrOld[i],arrNew[i])
}

but it didn't work.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

From the docs on .replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace):
"The replace() method returns a new string with some or all matches of a pattern replaced by a replacement."
This means that text.replace() doesn't manipulate the text variable. To fix this, simply do the following in your loop:
text = text.replace()
This will catch the changed text into the text variable. Without doing this, you are making the changes, but you are not using them (you forget them).

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use String.prototype.replaceAll():

var text = "this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot";
var arrOld = ["coffee", "apple", "banana", "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"]
for (let i = 0; i < arrOld.length; i++) {
    text = text.replaceAll(arrOld[i], arrnew[i]);
}
console.log(text);

And maybe also Array.prototype.map():

var text = "this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot";
var arrOld = ["coffee", "apple", "banana", "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];
arrOld.map((old, i) => text = text.replaceAll(old, arrnew[i]));
console.log(text);

about 4 years ago · Juan Pablo Isaza Denunciar

0

replace returns a new string instead of changing the old one

you can use reduce

also add RegExp because replace works only for the first match it found

const text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana, another banana ,carrot`;

var arrOld = ["coffee", "apple", "banana" , "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];

const resultWitoutRegexp =  arrOld.reduce((res, textToChange, i) => res.replace(textToChange, arrnew[i]) , text)

const result = arrOld.reduce((res, textToChange, i) => res.replace(new RegExp(textToChange, 'g'), arrnew[i]) , text)
console.log(resultWitoutRegexp)
console.log(result)

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