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']
JavaScript
x
6
1
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
2
3
arr.forEach(x => {
4
x.replace('123', '');
5
});
6
Advertisement
Answer
Use .map
instead, if you can – return the .replace
call in the callback:
JavaScript
1
4
1
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
2
3
const result = arr.map(x => x.replace('123', ''));
4
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:
JavaScript
1
4
1
let arr = ['he123llo', 'cats', 'wor123ld', 'dogs'];
2
3
arr.forEach((x, i) => arr[i] = x.replace('123', ''));
4
console.log(arr);