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.
>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);