· 5 min read
Why regex test() with the g flag returns true, then false
A JavaScript regex with the g flag keeps state in lastIndex, so test() alternates true and false. Here is why it happens and how to fix it.

A JavaScript regex with the g (global) flag remembers where its last match ended in a property called lastIndex, and test() starts its next search from there. Call test() twice on the same string and the second call starts past the first match, fails, and resets lastIndex to 0, so results alternate true, false, true. Remove the g flag when you only need a yes-or-no answer, and the regex test function becomes stateless again.
The bug is easy to miss because each call looks independent. It usually shows up as a filter that drops every second item, or a validation check that passes on one keystroke and fails on the next.
Reproduce it
const re = /cat/g;
console.log(re.test('cat'), re.lastIndex); // true 3
console.log(re.test('cat'), re.lastIndex); // false 0
console.log(re.test('cat'), re.lastIndex); // true 3
Same regex, same input, different answers. The version that tends to reach production is a shared regex inside a filter:
const hasAt = /@/g;
const inputs = ['a@x', 'b@y', 'c@z', 'd@w'];
console.log(inputs.filter((s) => hasAt.test(s)));
// [ 'a@x', 'c@z' ]
Every string contains @, but half of them are rejected. Drop the g and all four come back.
Why does test() with the g flag alternate between true and false?
A RegExp object is not just a pattern. It is an object with state, and lastIndex is that state: a number that says where the next search should begin. Two flags make the regex read and write it:
g(global): search fromlastIndexonward, and after a match, setlastIndexto the position just past it.y(sticky): the match must start exactly atlastIndex, andlastIndexis updated the same way.
When a search fails, lastIndex goes back to 0. So with /cat/g on 'cat', the first call matches at position 0 and leaves lastIndex at 3. The second call starts at position 3, finds nothing, returns false and resets to 0. The third call is back where the first one began.
This was designed for loops that walk through a string one match at a time with exec():
const re = /o/g;
re.exec('foo').index; // 1
re.exec('foo').index; // 2
re.exec('foo'); // null, lastIndex is now 0
That is useful when you want every match. It is a trap when you call test() and expect a fresh answer.
The state follows the regex, not the string
lastIndex is not tied to the string you passed in. If you reuse one regex across different strings, the position left behind by the first string applies to the second:
const digits = /\d+/g;
digits.test('abc 123'); // true, lastIndex = 7
digits.test('42'); // false, search starts at 7, past the end
'42' is clearly made of digits, but the search begins at index 7 of a two-character string and fails at once. This is why the bug often looks random: the result depends on whatever string the regex saw before.
It gets worse when the regex is defined at module level and used by several callers, such as a validator imported into many components or a regex in a shared utility. Any of them can leave lastIndex in a state that changes the next caller's result.
Which string methods read lastIndex?
Not every method respects the stored position. This table reflects what Node 22 returns for a regex with the g flag:
| Method | Uses existing lastIndex? | What happens to lastIndex |
|---|---|---|
re.test(str) | Yes | Set past the match, or reset to 0 on failure |
re.exec(str) | Yes | Same as test() |
str.match(re) | No, starts at 0 | Left at 0 after collecting all matches |
str.replace(re, x) | No, starts at 0 | Left at 0 |
str.matchAll(re) | No | Works on an internal copy; original unchanged |
str.search(re) | No | Restored to its previous value |
So match, replace and matchAll are safe with a global regex, because they either reset or copy it. test and exec are the two that carry state from one call to the next.
The y flag is stricter still. A sticky regex only matches at the exact position in lastIndex, so /a/y.test('ba') is false even though the string contains a.
How do you fix it?
Pick the option that matches what the code is actually asking.
You only need a yes-or-no answer. Remove the g flag. Without g or y, test() ignores lastIndex and always searches from the start:
const hasAt = /@/;
inputs.filter((s) => hasAt.test(s)); // all four
This is the right fix most of the time. The g flag in a test() call is often copied from a replace() that needed it.
You need the global flag for other reasons. Reset the position before each check:
function matches(re, str) {
re.lastIndex = 0;
return re.test(str);
}
You are matching a plain substring. You may not need a regex at all. str.includes('@') and str.startsWith('http') have no state and are easier to read.
You build the regex dynamically. Creating a new RegExp per call avoids shared state, at the cost of compiling it each time. If the pattern comes from user input, escape it first, as covered in RegExp.escape for safe dynamic regex.
You want every match. Use str.matchAll(re) instead of an exec() loop. It requires the g flag, works on a copy of the regex, and leaves the original alone.
const words = /\w+/g;
for (const m of 'one two three'.matchAll(words)) {
console.log(m[0], m.index);
}
A short code review rule helps here: a regex with g passed to test() or used inside filter, some or every deserves a second look.
Key takeaways
- A regex with
gorystores its position inlastIndex, andtest()andexec()start from there. - Repeated
test()calls on a global regex alternatetrueandfalseon the same input. - The stored position carries across different strings, so results depend on the previous call.
match,replaceandmatchAlldo not carry this state between calls;testandexecdo.- For a yes-or-no check, drop the
gflag or useincludes().
FAQ
Does this affect regex literals inside a function?
A regex literal inside a function body creates a new RegExp object each time the function runs, so lastIndex starts at 0 on every call. The problem appears when the regex is defined once outside the function and reused.
Is this a bug in JavaScript?
No. It is specified behavior and works the same in every modern browser, Node, Deno and Bun. The g flag means "continue from where the last match ended", and test() honors that.
Does String.prototype.split care about lastIndex?
No. split() works on an internal copy of the regex and ignores the g flag, so it gives the same result whether or not the flag is set.