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.
One picture is better, you know...
re_once = /([a-z])([A-Z])/
re_glob = /([a-z])([A-Z])/g
st = "aAbBcC"
console.log("match once="+ st.match(re_once)+ " match glob="+ st.match(re_glob))
console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st))
console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st))
console.log("exec once="+ re_once.exec(st) + " exec glob="+ re_glob.exec(st))
See the difference?
Note: To highlight, notice that captured groups(eg: a, A) are returned after the matched pattern (eg: aA), it's not just the matched pattern.
/regex/.exec()
returns only the first match found, while "string".match()
returns all of them if you use the g
flag in the regex.
See here: exec, match.