Мне нужно изменить этот текст:
var text = `this is an example text. 1coffee , 2 coffee , 1 apple, 2apple , ?banana ,carrot`;
используя эти 2 массива:
var arrOld = ["coffee", "apple", "banana" , "carrot"];
var arrnew = ["laptop", "keyboard", "mouse", "printer"];
чтобы получить такой результат:
`this is an example text. 1laptop , 2 laptop , 1 keyboard, 2keyboard , ?mouse ,printer`
Я пытался что-то вроде:
for (let i = 0; i < arrOld.length; i++) {
arrNew[i];
arrOld[i];
text.replace(arrOld[i],arrNew[i])
}
но это не сработало.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Из документов на .replace (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace):
«Метод replace() возвращает новую строку, в которой некоторые или все совпадения шаблона заменены заменой».
Это означает, что text.replace() не манипулирует текстовой переменной. Чтобы это исправить, просто выполните в своем цикле следующее:text = text.replace()
Это перехватит измененный текст в текстовую переменную. Без этого вы вносите изменения, но не используете их (вы их забываете).
Вы можете использовать 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.info(text);А может быть и 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.info(text);replace возвращает новый string вместо изменения старого
вы можете использовать reduce
также добавьте RegExp, потому что replace работает только для первого найденного совпадения
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.info(resultWitoutRegexp)
console.info(result)Вы можете попробовать это. Изменено из вашего кода.
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.info(text);Ах. IC Следует использовать регулярное выражение при замене вызова. text = text.replace(new RegExp(oldArray[i], "g"), newArray[i]);
Похоже, что из ожидаемого результата OP второй
coffeeтакже заменен наlaptop.