Justin Warkentin Justin Warkentin - 1 year ago 83
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download