exec
function will only search for the next match each time it is called. If you want to find all matches, you need to call it multiple times:
If your regular expression contains the "g" flag, you can use the exec method repeatedly to find successive matches in the same string.
To find all matches using exec
, you can do the following:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
match, matches = [];
while ((match = re.exec(str)) !== null) {
matches.push(match[0]);
}
Alternatively, you can simply utilize the match
method on the string `str`:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
matches = str.match(re);
Just a tip: Using the RegExp literal syntax /…/
is often more convenient: /[0-9]+/g
.