Justin Warkentin Justin Warkentin - 1 month ago 4
Javascript Question

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

If I run this:


I get this:

["a", "a"]

But if I run this:


Then I get the expected result of this:

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

What's the difference?


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.