Using replace string method inside forEach


I have an array full of strings which I’d like to loop over and replace any occurrences of ‘123’ with ”.

The desired result would be: ['hello', 'cats', 'world', 'dogs']

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach(x => {
  x.replace('123', '');


Use .map instead, if you can – return the .replace call in the callback:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

const result = => x.replace('123', ''));

If you have to mutate the array in-place, then take the index as well, and assign the .replace call back to that index in the array:

let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];

arr.forEach((x, i) => arr[i] = x.replace('123', ''));

Source: stackoverflow