How to Test Regex in JavaScript: test(), match(), exec(), and matchAll()
Four Ways to Test a Regex in JavaScript
JavaScript gives you four common methods to run a regular expression against a string: test(), match(), exec(), and matchAll(). They look similar but return very different things, and picking the wrong one is the source of many subtle bugs.
test(): The Fastest Yes/No Check
regex.test(string) returns a boolean. Use it when you only care whether something matches, such as form validation.
const emailOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(input);
// true or false
match(): Get the Matched Substring
string.match(regex) returns the first match (with capture groups) as an array, or null. Without the g flag it also gives you index, input, and named groups. With the g flag it returns an array of all matched substrings and loses group details.
"order #1024".match(/#(\d+)/);
// ["#1024", "1024"]
"a1 b2 c3".match(/[a-z]\d/g);
// ["a1", "b2", "c3"]
exec(): The Stateful Workhorse
regex.exec(string) returns one match at a time and advances the regex's lastIndex property. Call it in a loop to walk through all matches while keeping capture groups and indexes.
matchAll(): Iterate All Matches Safely
string.matchAll(regex) requires the g flag and returns an iterator of match objects, each with groups and index. It is the modern, loop-friendly replacement for manual exec() walks.
const re = /([a-z])(\d)/g;
for (const m of "a1 b2".matchAll(re)) {
console.log(m[1], m[2], m.index);
}
The lastIndex Trap With the g Flag
This is the part that bites people. When a regex has the g (or y) flag, test() and exec() are stateful: they remember lastIndex from the previous call and start searching there next time. Reusing the same regex object across calls causes alternating true/false results.
const re = /\d+/g;
re.test("12 34"); // true, lastIndex now 2
re.test("12 34"); // false, starts at index 2!
// Fix: create a fresh regex each time, reset re.lastIndex = 0,
// or use String.prototype.match / matchAll for stateless checks.
Pick the Right Tool
Use test() for validation booleans, match() for one-off substrings, matchAll() when you need all matches with groups, and exec() only when you explicitly want to drive iteration yourself. Always be aware of the g flag and lastIndex.
Test Regex Live in Your Browser
Want to experiment without redeploying? Paste your pattern and sample text into the free online regex tester on Regex Toolbox. It highlights matches in real time so you can see exactly where lastIndex and the g flag change the result.