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', '');
});
asked Dec 5, 2020 at 21:48
nandesuka
7991 gold badge13 silver badges31 bronze badges
1 Answer 1
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);
answered Dec 5, 2020 at 21:51
CertainPerformance
374k55 gold badges354 silver badges359 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
const replacedStrings = arr.map(word => word.replace(/123/g, ''))forEach()returnsundefined, you're supposed to useArray.prototype.map()insted and, by the way, it's better to use.replace(/123/g, '')if you want to replace all occurrences of unneeded substring