Using replace string method inside forEach

Tags:



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', '');
});

Answer

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

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

const result = arr.map(x => x.replace('123', ''));
console.log(result);

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', ''));
console.log(arr);


Source: stackoverflow