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:
var regex = new RegExp('a', 'g');
console.log(regex.test('a')); // true
console.log(regex.test('a')); // false
var regex = new RegExp('a', 'g');
console.log(regex.test('a')); // true
console.log(regex.test('a')); // false
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
ChooKing
ChooKing10mo ago
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.
ἔρως
ἔρως10mo ago
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.
ἔρως
ἔρως10mo ago
not that but that explains the idiotic behaviour