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

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

Leave a Comment