2

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', '');
});
2
  • 1
    const replacedStrings = arr.map(word => word.replace(/123/g, '')) 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 Commented Dec 5, 2020 at 21:53

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.