test() is the fastest way to ask “does this pattern match?” It returns true or false—nothing else. Use it in validation, filtering, and guard clauses when you do not need capture groups or match text.
01
Syntax
regex.test(str)
02
true
Match found
03
false
No match
04
Validate
Forms & input
05
vs exec
Boolean only
06
g flag
lastIndex
Fundamentals
Introduction
After you build a regular expression, the next step is running it against text. Sometimes you need the matched substring and capture groups—that is what exec() is for. Often you only need a yes-or-no answer: Is this a valid email shape? Does the filename end in .pdf? Does the log line contain ERROR? For those cases, test() is the right tool.
RegExp.prototype.test() searches a string for the pattern and returns a boolean. It is readable in conditionals, works with every flag, and is one of the most common regex calls in real JavaScript code.
Concept
Understanding the test() Method
regex.test(string) runs the pattern held by regex against string:
Match found — returns true. The pattern matches at least one substring of the input.
No match — returns false. The pattern cannot match anywhere in the string.
No match details — unlike exec(), you do not get text, groups, or index. Only the boolean.
Global regex — with the g or y flag, test() updates regex.lastIndex for the next call.
Coercion — non-string input is converted with ToString before matching.
💡
Beginner Tip
When validating an entire field (password, ZIP code, username), combine test() with start and end anchors: /^pattern$/. Without anchors, a partial match inside a longer string still returns true.
Usage
How to Use test()
Call test() on a RegExp object and pass the string to check. Use the result directly in if statements, ternary expressions, or .filter() callbacks:
Prefer test() when you only need a boolean. Switch to exec() or match() when you need the matched text or capture groups.
Foundation
📝 Syntax
JavaScript
regex.test(string)
Parameters
regex — the RegExp object with your pattern and flags.
string — the text to search (coerced to string if needed).
Return value
true if a match is found.
false if no match is found.
Cheat Sheet
⚡ Quick Reference
Goal
Code
Check for a match
/pat/.test(text)
Validate whole field
/^pat$/.test(text)
Case-insensitive check
/pat/i.test(text)
Reject invalid input
if (!rule.test(val)) …
Need match text
Use exec() or match()
Reset global regex
regex.lastIndex = 0
Compare
📋 test() vs exec() vs match()
Pick the method that returns the detail level you need.
test()
true / false
Quick boolean check
exec()
array or null
Groups + index
match()
string method
Convenient on strings
search()
index or -1
Position only
Hands-On
Examples Gallery
Open DevTools Console (F12) or use Try-it links. Examples cover basic checks, validation, negation, case-insensitive matching, and the global-flag lastIndex pitfall.
📚 Getting Started
Return true or false from a pattern check.
Example 1 — Basic Pattern Check
Test whether the word world appears in a sentence.
Anchors ^ and $ require the entire string to match. This pattern is a simplified shape check—production email validation usually needs a stricter rule or a dedicated library.
Example 3 — Reject Invalid Input with !
Use negation to block values that fail a digits-only rule.
JavaScript
const digitsOnly = /^\d+$/;
function validateAge(value) {
if (!digitsOnly.test(value)) {
return "Age must be digits only.";
}
return "OK";
}
console.log(validateAge("42")); // OK
console.log(validateAge("42abc")); // Age must be digits only.
The i flag makes matching case-insensitive. See also the i modifier page and ignoreCase property.
Example 5 — Global Flag and lastIndex
See why repeated test() calls on a global regex can surprise you.
JavaScript
const regex = /a/g;
console.log(regex.test("aba")); // true — match at index 0
console.log(regex.test("aba")); // true — match at index 2
console.log(regex.test("aba")); // false — lastIndex past end
regex.lastIndex = 0;
console.log(regex.test("aba")); // true — reset works
With the g flag, each test() advances lastIndex. The third call finds no further match. For simple boolean checks, omit g or reset lastIndex before reusing the regex.
Applications
🚀 Common Use Cases
Form validation — check emails, phone shapes, ZIP codes, and passwords.
Guard clauses — early-return when input fails a required pattern.
String methods like includes() work for literal text; use regex when patterns are needed.
Compatibility
Browser & Runtime Support
RegExp.prototype.test() has been part of JavaScript since ES3 and works identically in every modern runtime.
✓ Baseline · ES3+
RegExp test()
Supported in Chrome, Firefox, Safari, Edge, Internet Explorer, and all Node.js versions. Core regex API.
99%Universal API
Google ChromeSupported · Desktop & Mobile
Full support
Mozilla FirefoxSupported · Desktop & Mobile
Full support
Apple SafariSupported · macOS & iOS
Full support
Microsoft EdgeSupported · Chromium
Full support
Internet ExplorerNo native support · Use a polyfill
Polyfill
OperaSupported · Modern versions
Full support
Samsung InternetSupported · Android
Full support
BunSupported · JavaScript runtime
Supported
DenoSupported · JavaScript runtime
Supported
Node.jsSupported · Server runtime
Supported
Android WebViewSupported · Modern WebView
Full support
RegExp test()Excellent
Bottom line: Safe everywhere. Use test() for fast boolean pattern checks in validation and filtering.
Wrap Up
Conclusion
test() is the simplest way to run a regular expression against a string. It returns true or false—perfect for validation, filtering, and guard clauses. Add anchors for whole-field checks, watch lastIndex with the global flag, and reach for exec() when you need match details.
Next, learn about the legacy compile() method, or review exec() for capture groups and iteration.
Assume test() validates the entire string without anchors
Call test() when you need capture group values
Share one global regex across concurrent code without resetting
Rely on regex alone for security-critical sanitization
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about test()
Boolean pattern checks made simple.
5
Core concepts
📝01
Syntax
regex.test(s)
API
✅02
true
Match found.
Result
❌03
false
No match.
Result
🔒04
^…$
Full field.
Validate
⚠05
g flag
lastIndex.
Pitfall
❓ Frequently Asked Questions
test() returns true if the pattern matches anywhere in the string, or false if it does not. Unlike exec(), it does not return match text or capture groups—only a boolean.
test() answers yes or no with a boolean. exec() returns detailed match data—full text, capture groups, index, and input—or null when there is no match. Use test() for validation; use exec() when you need the matched content.
Yes. That is the most common pattern: if (/^\d+$/.test(value)) { … }. Combine with anchors (^ and $) when the entire field must match the pattern.
Yes. /hello/i.test('HELLO') returns true because the i flag makes matching case-insensitive.
On a global regex, each test() call advances lastIndex. Repeated calls may return false even when matches exist. Reset with regex.lastIndex = 0 before re-testing, or avoid g when you only need a boolean check.
No. test() only reads the string you pass in. It may update lastIndex on the RegExp object when the g or y flag is set, but the input string is never modified.
Did you know?
Under the hood, test() calls the same matching engine as exec() but throws away the result array. That is why performance is similar for a single check—choose based on whether you need the boolean or the match details.