var digit = /\d/g;
console.log(digit.exec("here it is: 1"));
console.log(digit.lastIndex);
console.log(digit.exec("and now: 1"));
var digit2 = /\d/g;
console.log(digit2.exec("and now: 1"));
console.log(digit2.lastIndex);
console.log(digit2.exec("here it is: 1"));
If you run the above you will see that the exec adds a lastindex
property to the regex and uses that as the starting index for the next search. When it is the shorter string first (in terms of finding the first digit), then it finds the digit in both exec's. When the longer string is first, the lastIndex
is actually past the digit in the second (shorter) string and so it returns null
.
This only happens if you use the / /g flag. Without g
it would work as you expect since the lastIndex
is reset to 0 for each exec
:
var digit = /\d/;
console.log(digit.exec("here it is: 1"));
console.log(digit.lastIndex);
console.log(digit.exec("and now: 1"));