admin管理员组

文章数量:1400771

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

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', '');
});
Share Improve this question asked Dec 5, 2020 at 21:48 nandesukanandesuka 7991 gold badge13 silver badges31 bronze badges 2
  • 1 const replacedStrings = arr.map(word => word.replace(/123/g, '')) – Yevhen Horbunkov Commented Dec 5, 2020 at 21:51
  • forEach() returns undefined, you're supposed to use Array.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 – Yevhen Horbunkov Commented Dec 5, 2020 at 21:53
Add a ment  | 

1 Answer 1

Reset to default 7

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);

本文标签: javascriptUsing replace string method inside forEachStack Overflow