Interesting test of Javascript RegExp [duplicate]
Solution 1:
When you use a global flag on a JS RegExp the "test" and "exec" methods each halt at the first match but keep a pointer to where they stopped searching in the string. That pointer can be inspected on the lastIndex
property. When you call "test" or "exec" again it begins searching for a match starting at the lastIndex
.
So, when you test a RegExp on a string that matches the entire string the lastIndex is set to the end of the string. The next time you test it starts at the end of the string, returns false
, and sets lastIndex
back to zero.
The MDC has a decent explanation of this behavior.