Browsers & softwarePractical guides

Why does the same JavaScript regex test alternate true and false?

If the same RegExp object has the g flag, inspect lastIndex. A successful test saves a position for the next call. Repeated tests of unchanged text can therefore return true, false, true.

Close-up of vintage typewriter keys on a black background
Illustrative photo: Dani Adkins · Unsplash LicenseStock illustration, not a software screenshot, device review or operation record.

Key Takeaways

For independent validation, normally use a regex without g or explicitly reset lastIndex before each test. For intentional scanning, preserve the position and define termination. Record object reuse, flags and before/after indices before changing character classes or anchors.

In this article

Check object reuse, not just the pattern text

The test reference identifies stateful behaviour with g or y. An object created outside a loop is not equivalent to a new object created for each iteration. Printing only the pattern can hide that distinction.

This page concerns search position between calls. The existing named-group replacement guide checks captured content and replacement output, which is a separate task.

Trace all three calls

This is an authored, fixed JavaScript specimen, executed in Node.js for the editorial check. The input is always cat, with no spaces or newlines. The table gives the observed values, and the script lets readers reproduce them in their own test environment.

The first match starts at zero and ends at three. The second starts at three, where ^cat$ cannot match, then fails and resets the index. The third starts at zero again. Consult the lastIndex reference for the position-update rules.

Reuse one object

const re = /^cat$/g;
console.log([1, 2, 3].map(() => {
  const before = re.lastIndex;
  const matched = re.test("cat");
  return { before, matched, after: re.lastIndex };
}));
Reproduce in a development test environment; repeated site-button clicks are a different setup.

Observed trace for the fixed specimen
CalllastIndex beforetest resultlastIndex after
10true3
23false0
30true3

Choose between validation and scanning

If three fields must each equal cat, use /^cat$/.test(value). All three cat fields should pass; add Cat and cat! as failures so the repair does not accidentally relax whole-string validation.

If a reusable g object is required, set re.lastIndex=0 before each independent input and make that precondition explicit in the function or tests. An intentional scanner should instead preserve its position and handle empty matches and termination. The y flag is also stateful but requires matching at the specified position; it is not a synonym for g.

Why a web tester can keep succeeding

The current regex tester creates a new RegExp for each operation and collects matches with matchAll, adding g when absent. Running it again can compare match lists, but does not repeatedly call the same object retained by your application.

Keep a minimal script, flags and index trace from the failing program, then independently check what the pattern matches. The format-versus-semantics guide is useful for surrounding code: successful formatting does not establish correct object lifetime.

Further reading & sources

Put the guide into practice

Open the relevant tool, preview the result and check your exported file.