0

Hi so assume I have a match() output array where all elements are strings, and i want to replace some of the text inside those strings but using forEach() instead of a regular for loop.

lets suppose the output array is

stringsArray = ["<div>some text here</div>","<div>Some other text here</div>"]; 

again the code above is the output of a match() of some text. which prints correctly in the console.

let parsedArray = stringsArray.forEach(element => element.replace(/<div>|<\/div>/g,'\n'));

for some reason the code above doesn't work, console.log(parsedArray) comes back undefined.

should i use a regular for loop instead, if so why?

zhisme
  • 2,368
  • 2
  • 19
  • 28
Dziban
  • 19
  • 3

1 Answers1

0

forEach() just iterates through the array. Changes to element are only made to that local copy, and are not returned.

Try map(), which lets you return an altered element:

let parsedArray = stringsArray.map(element => { return element.replace(/<div>|<\/div>/g,'\n') });
kmoser
  • 8,780
  • 3
  • 24
  • 40