3

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"]?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Yosi
  • 2,936
  • 7
  • 39
  • 64

2 Answers2

6

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.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
2

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

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test will also advance the lastIndex property). – 王奕然 Aug 06 '13 at 07:35