Results.

SCEPTRA.TECH

JavaScript Regex Test Flips Between True and False? Check lastIndex Before Retrying

Three calls of a global cat regex return true false true as lastIndex advances and resets

The same JavaScript check returns true, then false, then true for an unchanged string. Before blaming a stale input or a framework render, inspect the regular expression's flags and lastIndex. A RegExp object with the global or sticky flag carries matching state between calls. A boolean result does not mean the operation is stateless.

Make the changing state visible

Run this short example without a browser framework:

const pattern = /cat/g;
for (let i = 0; i < 3; i++) {
  console.log(pattern.test('cat'), pattern.lastIndex);
}
// true 3
// false 0
// true 3

The first successful match ends at index 3. The next call starts searching there, finds no further match and resets lastIndex to zero. The third call can match again. The g flag does not mean that each call independently checks the whole string from its beginning.

This particular input alternates, but not every global pattern will alternate. A longer string may contain several matches, and its sequence of results will differ. Inspect the index instead of turning the symptom into a general rule.

For independent yes-or-no checks, leave off g

A filter can expose the bug because it reuses one pattern across separate inputs:

const values = ['cat', 'cat', 'cat'];
const shared = /cat/g;
console.log(values.filter(value => shared.test(value)));
// ['cat', 'cat']

const containsCat = /cat/;
console.log(values.filter(value => containsCat.test(value)));
// ['cat', 'cat', 'cat']

For this independent substring check, the non-global pattern is the simpler choice. It does not need a remembered scan position. Removing g is a change to review at the call site, not a project-wide replacement: another operation may intentionally need all matches.

The example asks whether cat occurs anywhere. It is not a complete validator for an identifier, filename or user-submitted field. Define the accepted format separately rather than assuming the state fix makes the pattern correct.

If you must reuse a global pattern, reset deliberately

const shared = /cat/g;
function containsCat(value) {
  shared.lastIndex = 0;
  return shared.test(value);
}

This resets before each independent check, including checks against different strings. A new input does not automatically reset lastIndex. I would keep a separate non-global pattern for a simple predicate rather than share mutable scan state across unrelated callers. Where state is intentional, its owner should be clear.

Sticky matching needs a separate decision

The y flag also uses lastIndex, but it requires a match exactly at that position rather than searching later positions. For /cat/y, testing 'a cat' from index zero fails. Setting lastIndex to 2 lets it match and advances the index to 5. That behavior can be useful for token-by-token parsing; stripping y would change the parser's rule.

What I checked locally

I ran the examples in Node.js 22.23.4 with ordinary built-in RegExp objects. The repeated test produced the three boolean/index pairs shown, the global filter kept two entries, the non-global and reset variants kept all three, and the sticky example matched only at the chosen offset. No production input, framework integration or performance benchmark was tested.

When a repeated check surprises you, log the input, flags and lastIndex together. Then decide whether the operation is an independent predicate or a continuing scan. Fix that ownership boundary before adding retries that merely hide the changing state.

Sources

Comments