15

Can anyone tells me why does't the second snippet catchs the 'groups' when use g flag ?

  "123".match(/(\d{1})(\d{1})/)    // returns  ["12", "1", "2"]
  "123".match(/(\d{1})(\d{1})/g)   // returns ["12"]   (where's 1 and 2 ?)

console.log("123".match(/(\d{1})(\d{1})/))    // returns  ["12", "1", "2"]

console.log("123".match(/(\d{1})(\d{1})/g))   // returns ["12"]   (where's 1 and 2 ?)
Tom Doodler
  • 1,471
  • 2
  • 15
  • 41
johnny_trs
  • 233
  • 1
  • 2
  • 6

1 Answers1

23

As per MDN docs :

If the regular expression does not include the g flag, returns the same result as RegExp.exec(). The returned Array has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.


If you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.

var myRe = /(\d)(\d)/g;
var str = '12 34';
var myArray;
while (myArray = myRe.exec(str)) {
  console.log(myArray);
}
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Note that defining the regex as a variable is required to make this work. You will end up with an infinite loop otherwise (e.g. `while (myArray = /(\d)(\d)/g.exec(str))`). – pmrotule Jul 23 '21 at 08:13