2

The code snippet

'a b'.match(/a|b/ig)

returns

["a", "b"]

which is totally expected as we are searching for substring with either 'a' or 'b' but why does

'a b'.match(/(a|b)/i)

return

["a", "a"]

as output, how does a gets matched twice? Shouldn't it just be ["a"] as for 'a b'.match(/a|b/i)

Abhay
  • 110
  • 2
  • 9

2 Answers2

2

In 'a b'.match(/(a|b)/i) you have a capture group that doesn't exit in your first example. The resulting array contains the value for the full match (i.e. a) and the value for the first capture group (i.e. a).

That's why you have ["a", "a"]

Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    That's the correct explanation I guess, can be verified with following example `'a bc'.match(/(a|b)c/i) ` , this returns `["bc", "b"]` – Abhay Nov 30 '18 at 18:05
2

The answer here is in the documentation:

If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

Therefore 'a b'.match(/(a|b)/i) is the same as /(a|b)/i.exec('a b') which will return the matched string and the captured group so, one capturing group, one additional array entry.

On the other hand:

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • this is an example of your first doc snip ["a", "a", index: 0, input: "a b", groups: undefined], I am unable to the answer to this question though even through the second snip – Abhay Nov 30 '18 at 18:00
  • Okay, now that I know the answer, I can see that your question explains why with `g` flag only `["a"]` was returned. I was actually trying to find why second code returns `["a", "a"]`, your answer was right too. Thanks. – Abhay Nov 30 '18 at 18:09