I have the following code :
var str = "4 shnitzel,5 ducks";
var rgx = new RegExp("[0-9]+","g");
console.log( rgx.exec(str) );
The output on chrome and firefox is ["4"]
.
Why don't I get the result ["4","5"]
?
I have the following code :
var str = "4 shnitzel,5 ducks";
var rgx = new RegExp("[0-9]+","g");
console.log( rgx.exec(str) );
The output on chrome and firefox is ["4"]
.
Why don't I get the result ["4","5"]
?
exec
does only search for the next match. You need to call it multiple times to get all matches:
If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string.
You can do this to find all matches with exec
:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
match, matches = [];
while ((match = re.exec(str)) !== null) {
matches.push(match[0]);
}
Or you simply use the match
method on the string `str:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
matches = str.match(re);
By the way: Using the RegExp literal syntax /…/
is probably more convenient: /[0-9]+/g
.
exec()
always only returns one match. You get further matches you need to call exec repeatedly.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec