Skip to content
Advertisement

Using replace string method inside forEach

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

Advertisement

Answer

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

JavaScript

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
Advertisement