Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can try this. Modified from your code.

const oldArray = ["coffee", "apple", "banana" , "carrot"];
const newArray = ["laptop", "keyboard", "mouse", "printer"];

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

const { length } = oldArray
for (let i = 0; i < length; i++) {
  text = text.replace(oldArray[i], newArray[i]);
}

console.log(text);

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading