JavaScript RegExp test() Method

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is test()?

RegExp.prototype.test(string) answers one question: does this pattern match? It returns true or false — no match text, no groups. Ideal for validation and if guards.

Remember
regex.test(string)  → true | false

/world/.test("hello world")  → true
/world/.test("hello there")  → false

/^\d+$/.test("42")           → true   (whole string)
/hello/i.test("HELLO")       → true   (ignore case)

Need match text? → use exec() or String.match()
UsePrefer
Yes / no checkregex.test(str)
Match detailsregex.exec(str)
Whole-field validation/^…$/.test(value)

How to Use test()

Build a regex, call test with a string, and branch on the boolean.

  1. Create a pattern with a literal (/…/) or new RegExp(…).
  2. Call regex.test(string) — returns true or false.
  3. Add ^ and $ when the entire value must match.
  4. Skip the g flag for simple checks (or reset lastIndex).
PieceRequired?Role
RegExpYesPattern to test against
stringYesInput to search (coerced to string)
Flags (i, m, …)OptionalChange matching rules; avoid g for simple checks

Pseudocode

Pseudocode
regex = /pattern/
input = given string

if pattern finds a match in input:
    return true
else:
    return false

// with g or y flag:
//   also update regex.lastIndex for the next search
// without g:
//   lastIndex is not used for sticky searching

Cheat Sheet

Keep these facts handy while writing boolean pattern checks.

TopicDetail
Syntaxregex.test(string)
Returntrue or false only
Search scopeAnywhere in the string (unless anchored)
Whole field/^pattern$/.test(value)
vs exec()Boolean vs match details
g flag trapAdvances lastIndex on each call
StandardES3+ (universal)

Live Preview

Pick a pattern and a sample string to see what test() returns.

Browser demo of RegExp.prototype.test — same idea as the examples below.

Result
pattern = /world/
text    = "hello world"
test()  → true

/* pattern found somewhere in the string */

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

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

  1. Create the pattern. /world/ looks for that literal text.
  2. Match anywhere. Without anchors, a mid-string hit still counts.
  3. First call succeeds. "hello world" contains world → true.
  4. Second call fails. "hello there" has no match → false.

Example 2 — Validate Digits-Only Input

Use anchors and ! to accept or reject a whole field.

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

  1. Anchor the field. ^ and $ require every character to be a digit.
  2. Negate for errors. !digitsOnly.test(value) is true when validation fails.
  3. Valid input. "42" matches → return "OK".
  4. Invalid input. "42abc" fails the whole-string rule → error message.

Example 3 — 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

  1. g remembers position. Each successful test() advances lastIndex.
  2. First two hits. Matches at indexes 0 and 2 in "aba".
  3. Third call fails. Search starts past the end → false.
  4. Reset to reuse. Set lastIndex = 0, or omit g for simple boolean checks.

Edge Cases & Pitfalls

Check these before relying on test() in real projects.

trap

Avoid g for simple boolean checks

Global regexes update lastIndex. Prefer a non-global pattern, or reset lastIndex before each reuse. See the g modifier.

partial

Without anchors, mid-string matches count

/\d+/.test("abc42") is true. Use /^\d+$/ when the whole field must be digits.

coercion

Non-strings are coerced

/2/.test(42) becomes a string check on "42". Pass strings explicitly when clarity matters.

details

test() does not return match text

Need groups or the matched substring? Use exec() or String.prototype.match.

Browser & Runtime Support

RegExp.prototype.test() is part of core JavaScript (ES3+). It works everywhere without polyfills.

✓ Baseline · ES3+

RegExp.prototype.test()

Supported in every modern and legacy browser, plus all Node.js versions. Universal boolean pattern 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
test() Excellent

Bottom line: Safe everywhere. Prefer test() for yes/no checks; reach for exec() when you need match details.

Performance Notes

ApproachCostBest for
regex.test(str)Stops at first matchValidation, guards, filters
regex.exec(str)Builds match objectWhen you need groups / index
str.match(/…/g)Finds all matchesCollecting every hit

For a pure boolean check, test() is the lightest choice — it can stop as soon as one match is found. Keep patterns simple and anchored when validating short form fields.

Key Takeaways

  • Role: test() returns only true or false.
  • Validation: use /^…$/.test(value) for whole fields.
  • vs exec: need groups or text? Call exec() instead.
  • Trap: skip g for simple checks, or reset lastIndex.

One line: test() is the yes/no regex tool — perfect for if guards, risky with a sticky g flag.

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.

Next: compile() (deprecated)

compile() is deprecated — read why and what to use instead.

compile() notes →

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.

11 people found this page helpful