3

var re = /\d(\d)/g;
var str = '123';
var match;
var results = [];

while (match = re.exec(str)) {
  results.push(+match[1]);
}
console.log(results);

Instead of [2, 3] as I would expect, it gives only [2] I cannot figure this out. Why doesn't the 23 match the regex and give the 3 as the capture group?

Barmar
  • 741,623
  • 53
  • 500
  • 612
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

2 Answers2

2

This is because the string 12 is matched in the first run of exec, captured parenthesis is 2 which is appended to results variable and lastIndex property of re object is updated to 2

In the second run of exec, re.lastIndex is 2 which means begin matching source string at index 2 , So re has string 3 which clearly doesn't match the pattern /\d(\d)/ and exec returns null, while loop is exited and results array just contains 2

Varinder Singh
  • 1,570
  • 1
  • 11
  • 25
0

How to do overlapping matches:

var re = /\d(?=(\d))/g;
var str = '123';
var match;
var results = [];

while (match = re.exec(str)) {
  results.push(+match[1]);
}
console.log(results);