Why does the second part of this regex not match?

Viewed 115

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?

2 Answers

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

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);

Related