Justin Warkentin Justin Warkentin - 2 months ago 7
Javascript Question

What is the difference between RegExp’s exec() function and String’s match() function?

If I run this:

/([^\/]+)+/g.exec('/a/b/c/d');


I get this:

["a", "a"]


But if I run this:

'/a/b/c/d'.match(/([^\/]+)+/g);


Then I get the expected result of this:

["a", "b", "c", "d"]


What's the difference?

Answer

exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:

var re = /[^\/]+/g;
var match;

while (match = re.exec('/a/b/c/d')) {
    // match is now the next match, in array form.
}

// No more matches.

String.match does this for you and discards the subexpressions' (named or captured groups) results.