DEV Community

Discussion on: Can you find the bug in this piece of code? - RegExp edition 🌍

Collapse
 
thebatman1 profile image
Mrinmay Mukherjee

Using the g(global) flag with .exec stores the index up to which the pattern matches. If the pattern does not match, the index is reset to 0.

If the previous search was successful, the next search starts after the stored index, even though the string is different. This is because the regular expression stores the matched index. I encountered this bug while writing an input validator. Took me half a day to figure this out. 😅😅

Here is the explanation from the docs

So for the above code:

  1. 'test_1' matches. So the stored index is 5.
  2. 'test_1' does not match, since the pattern matching starts at index 5, which is just an empty string. So the stored index becomes 0.
  3. 'test_2' matches. So the stored index becomes 5.
  4. 'other_test' does not match. So the stored index becomes 0.
  5. 'some_file' matches.

Thus the output is:

true
false
true
false
true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nombrekeff profile image
Keff

Great breakdown, thanks for taking the time to explain it in such detail!!