3

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 ?.

KiRa
  • 924
  • 3
  • 17
  • 42
  • 1
    read the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) for why this happens – Jaromanda X Feb 17 '17 at 01:38
  • Closely related: [Why RegExp with global flag in Javascript give wrong results?](https://stackoverflow.com/questions/1520800/why-regexp-with-global-flag-in-javascript-give-wrong-results) – apsillers Feb 17 '17 at 01:58

1 Answers1

6

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"));
rasmeister
  • 1,986
  • 1
  • 13
  • 19
  • If i understand it correctly the index form the first console will be use in the second console?. For example the index of the first console is 13 and running the second console index is 10 so it won't find it that's why the result is null?. Correct me if i'm wrong. – KiRa Feb 17 '17 at 01:49
  • Yes you are correct. `lastIndex` provides the starting point for the next search. So the second `exec` will ignore the first 10 characters, for example. With the global setting, it is expected that you will repeat searches on the same string until you get them all. In this case, you are switching strings but the `lastIndex` still takes effect. – rasmeister Feb 17 '17 at 01:53