It keeps track of the last match, so subsequent .test() calls start from where the last one left off. You can fix it by removing the g flag from all the regex patterns in BADGE_PATTERNS. Or, if you need the global flag for other reasons, you could reset pattern.lastIndex = 0 before each pattern.test() call.
Spot the Bug answer: The regular expressions use the global flag ‘g’, which causes the ‘test’ method to maintain state across calls.
The fix:
Remove the ‘g’ flag from all regular expressions in BADGE_PATTERNS.
Why:
When a regex with the ‘g’ flag is used with ‘test’, its ‘lastIndex’ property is updated after each match. Subsequent calls to ‘test’ will start searching from ‘lastIndex’, leading to alternating results (true, false, true, false) if the string matches, because it will find a match, then not find one from the new ‘lastIndex’, then reset and find one again.
That lastIndex behavior with the g flag is such a classic edge case. It’s so subtle, especially if you’re not expecting it.
I just avoid g with test() entirely because of this. String.prototype.matchAll() is my go-to if I need to find all occurrences and still get the capture groups.