Skip to content

Instantly share code, notes, and snippets.

@joemaller
Created April 21, 2017 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaller/1b2b9eb36ea743a1f1b1178ec93d1954 to your computer and use it in GitHub Desktop.
Save joemaller/1b2b9eb36ea743a1f1b1178ec93d1954 to your computer and use it in GitHub Desktop.
RegExp.exec and String.match are the same, right?

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 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.

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.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment