RegExp with g flag with weird behaviour. why?
i was debugging a bug and found this incredibly weird behaviour with a regex.
the following code was returning
false
on things that obviously match:
after trial and error, i found that re-using the same object with the g flag caused the behaviour above.
removing the g flag makes it work properly.
(using a new literal regex object fixes it too, but what i was debugging can't be made into a literal regex, since it is dynamically generated.)
is there any reason for this behaviour?
mdn doesnt have anything obvious that could clue that this behaviour could happen.3 Replies
Did you read MDN? It explains how the behavior is different when using the global flag. If you do it a third time, you will get true again, because it resets. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
RegExp.prototype.test() - JavaScript | MDN
The test() method of RegExp instances executes a search with this regular expression for a match between a regular expression and a specified string. Returns true if there is a match; false otherwise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global <-- i read this
RegExp.prototype.global - JavaScript | MDN
The global accessor property of RegExp instances returns whether or not the g flag is used with this regular expression.
not that
but that explains the idiotic behaviour