0

Can anyone explain why "script" is part of the output array and how this regex is interpreted in the split function?

console.log(
  "is javascript my favorite language?".split(/JAVA(Script)/i)
);

outputs

["is ", "script", " my favorite language?"]
Vivek Kumar
  • 419
  • 4
  • 12

1 Answers1

2

As MDN's docs say:

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

java is matched, but not captured, whereas script is captured in a group, so it's included in the resulting array.

Any captured groups will be included, as you can see:

console.log(
  "is javascript my favorite language?".split(/JAVA(Script)( )(my)/i)
)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320