Why your regex in JavaScript works every other time — and what the g flag has to do with it

A form validates an email. The first time you enter an address — fine. You hit "Submit" again with the same address — "Invalid email". Third time — fine again.
The address didn't change. The regex didn't change. You check in the console:
const re = /cat/g
re.test('cat') // true
re.test('cat') // false
re.test('cat') // true
Same string, same regex — and the answer flips. It's not magic and not a browser bug. A regex with the g flag has memory. Below are three common causes, starting with the most frequent. For each — how to confirm it and how to fix it.
Cause 1. The g flag and a shared test()
What happens. The g (global) flag means "find all matches, one after another". To search one after another, the regex remembers where it stopped. That number lives in the lastIndex property.
Let's walk through the example above:
- The first
test('cat')searches from position 0. Found it. StoredlastIndex = 3— the end of the match. - The second call searches from position 3. The string
'cat'has already ended there. Not found —false. ResetlastIndexto 0. - The third call searches from zero again —
true.
Hence "every other time". It hurts most inside filter:
const re = /cat/g
['cat', 'cat', 'cat'].filter(w => re.test(w))
// ['cat', 'cat'] — one got lost
AI models often add g "just in case". For a yes/no check you don't need it at all.
How to confirm. Log re.lastIndex before and after the call. Non-zero after a true — that's it.
How to fix. The simplest way is to drop g:
const re = /cat/ // without g, test() has no memory
Need the flag for something else? Then reset the position before each check: re.lastIndex = 0. Or create the regex inside the function instead of outside. The y (sticky) flag has the same memory.
Cause 2. One regex on different strings
What happens. Same memory, different symptom. After a long string lastIndex stays large. The next string is shorter — and the search starts past its end:
const re = /cat/g
re.test('my black cat') // true, lastIndex = 12
re.test('cat') // false — searches from position 12
On a server this looks scarier. The regex is declared at the top of a module, shared by everyone. One user sends a long string — the next user's validation fails. Nearly impossible to reproduce locally: "works on my machine".
How to confirm. Find regexes with g declared outside functions and see where they're used with test() or exec(). A project-wide search for /g helps. How to search a big codebase is in how to find code in a big project.
How to fix. Same as cause 1. For "does this string match" you never need the g flag.
Cause 3. An exec() loop hangs
What happens. A hand-written loop to find every match:
const re = /\d+/ // forgot g
let m
while ((m = re.exec('a1 b22 c333'))) {
console.log(m[0])
}
Without g the regex has no memory. It finds the first match — '1' — every time, and the loop spins forever. The tab freezes. More on such loops in why my loop runs forever.
There's a reverse variant too — with g, but the regex can match emptiness, like /a*/g. An empty match doesn't advance lastIndex. The loop is stuck again.
How to confirm. The tab froze on a search? Add a counter to the loop and break after a hundred iterations. Look at the output. The same match over and over — that's it.
How to fix. Don't write the loop by hand. Use matchAll:
for (const m of 'a1 b22 c333'.matchAll(/\d+/g)) {
console.log(m[0]) // '1', '22', '333'
}
matchAll tracks the position itself and handles empty matches correctly. And it won't forgive a missing g. You get an error right away instead of a silent hang: matchAll called with a non-global RegExp argument. replaceAll has the same guard.
A short cheat sheet
Which tool for which job:
- does the string match —
re.test(str)withoutg; - first match —
str.match(re)withoutg; - all matches as a list —
str.match(re)withg; - all matches with groups —
str.matchAll(re)withg; - replace everything —
str.replaceAll(re, ...)withg.
str.match and str.replace start from zero on their own. lastIndex doesn't trip them up — the trap belongs only to test() and exec(). How to read errors like the one matchAll throws is in how to read an error message.
Why does regex.test() return false the second time?
Because the regex has the g or y flag. After a successful search it stored the position in lastIndex and started the next search from there. Drop the flag or reset re.lastIndex = 0.
Do I need the g flag to validate an email or phone number?
No. Format checks need ^ and $ at the edges, and g only hurts. It's for finding or replacing many matches in a text.
Does lastIndex affect str.match()?
No. match, replace and split start from zero on their own. The memory trap belongs only to the regex's own methods: test() and exec().
The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.





