Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the second console log return null?

I don't get it why the second console.log returns a null while the first console returns 1

Code Source

var digit = /\d/g;

console.log(digit.exec("here it is: 1"));

console.log(digit.exec("and now: 1"));

If I switch it they both returns 1

var digit = /\d/g;
console.log(digit.exec("and now: 1"));
console.log(digit.exec("here it is: 1"));

I am starting to learn RegEx by reading the link I provided above.

What does exec really do ?.

like image 269
KiRa Avatar asked Feb 01 '26 01:02

KiRa


1 Answers

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"));
like image 112
rasmeister Avatar answered Feb 03 '26 17:02

rasmeister