JavaScript RegExp test() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Boolean check

What You’ll Learn

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

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.

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.

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:

JavaScript
if (/^\d+$/.test(input)) {

  console.log("Digits only");

}



const hasError = /ERROR/i.test(logLine);

const valid = /^[\w.-]+@[\w.-]+\.\w+$/.test(email);



items.filter((item) => /\.pdf$/i.test(item));

Prefer test() when you only need a boolean. Switch to exec() or match() when you need the matched text or capture groups.

📝 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.

⚡ Quick Reference

GoalCode
Check for a match/pat/.test(text)
Validate whole field/^pat$/.test(text)
Case-insensitive check/pat/i.test(text)
Reject invalid inputif (!rule.test(val)) …
Need match textUse exec() or match()
Reset global regexregex.lastIndex = 0

📋 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

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.

JavaScript
const regex = /world/;



console.log(regex.test("hello world"));  // true

console.log(regex.test("hello there")); // false
Try It Yourself

How It Works

test() searches anywhere in the string. "hello world" contains world, so the result is true. No match details are returned—only the boolean.

📈 Practical Patterns

Validation, rejection, flags, and pitfalls.

Example 2 — Validate an Email Shape

Check whether input looks like a basic email address.

JavaScript
const emailRule = /^\w+@\w+\.\w+$/;



console.log(emailRule.test("ada@example.com")); // true

console.log(emailRule.test("not-an-email"));    // false

console.log(emailRule.test("a@b.c"));           // true
Try It Yourself

How It Works

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.
Try It Yourself

How It Works

!regex.test(value) is a common validation idiom. When test() returns false, the negated condition is true and you can show an error message.

Example 4 — Case-Insensitive Match with the i Flag

Find a word regardless of letter case.

JavaScript
const regex = /hello/i;



console.log(regex.test("hello world"));  // true

console.log(regex.test("HELLO World"));  // true

console.log(regex.test("hi there"));     // false
Try It Yourself

How It Works

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
Try It Yourself

How It 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.

🚀 Common Use Cases

  • Form validation — check emails, phone shapes, ZIP codes, and passwords.
  • Guard clauses — early-return when input fails a required pattern.
  • Filtering arraysitems.filter(item => /pat/.test(item)).
  • Feature detection in text — does a log line contain ERROR or WARN?
  • File type checks — test extensions like /\.pdf$/i.
  • Permission flags — quick pattern checks before heavier parsing with exec().

Important Considerations

  • Partial vs full match — without ^…$, test() succeeds on substring matches.
  • Global flag side effectg and y update lastIndex on each call.
  • No capture data — use exec() when you need groups or matched text.
  • Not a security boundary — regex validation alone does not sanitize HTML or prevent injection.
  • Reuse shared regexes — reset lastIndex on global objects before a fresh scan.
  • Overly complex patterns — keep validation regex readable; split complex rules into steps.

🧠 How test() Searches a String

1

Coerce input

The string argument is converted with ToString if it is not already a string.

Input
2

Run pattern

The engine searches from the start position (or lastIndex for global/sticky regexes).

Engine
3

Return boolean

On success, return true and update lastIndex when applicable. On failure, return false.

Result
4

Use in conditionals

Plug the boolean directly into if, ternary, or filter logic—no null checks needed.

📝 Notes

  • test() is implemented in terms of exec() internally—it discards match details.
  • Previous topic: exec() for full match data.
  • Next topic: compile() legacy method.
  • For whole-field rules, pair with ^ and $ anchors.
  • See g modifier for global matching behavior.
  • String methods like includes() work for literal text; use regex when patterns are needed.

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 Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
RegExp test() Excellent

Bottom line: Safe everywhere. Use test() for fast boolean pattern checks in validation and filtering.

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.

💡 Best Practices

✅ Do

  • Use test() when you only need true or false
  • Add ^…$ for whole-field validation
  • Store reusable patterns in named constants
  • Reset lastIndex before reusing global regexes
  • Prefer readable patterns over clever one-liners

❌ Don’t

  • Use g when a single boolean answer is enough
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about test()

Boolean pattern checks made simple.

5
Core concepts
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.

Continue to compile()

Learn about the legacy RegExp compile method and modern alternatives.

compile() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful