In JavaScript RegExp.exec()
and String.match()
should be interchangeable so long as the inputs are the same. Right?
const pat = /(dog).*(bird)/g;
const str = 'dog cat bird';
const foo = str.match(pat);
const bar = pat.exec(str);
Right, so why are foo
and bar
different?
foo
is an array containing the original string. That's it. Not what I was expecting;
['dog cat bird']
bar
contains the expected, complete RegExp result:
['dog cat bird', 'dog', 'bird', index: 0, input: 'dog cat bird']
What happened?*
That little g
flag at the end of the RegExp? It completely changes the behavior of String.match
. From MDN's String.match
docs:
If the regular expression does not include the
g
flag,str.match()
will return the same result asRegExp.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.
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 returnsnull
.
In 21 years of JavaScript, I never saw that before now.
String.match
might be a bit too quirky for me, I'll be sticking to explicit RegExp methods.