Course contentsShow
← JavaScript
Lesson 1666 of 2,72336. Regular ExpressionsFree lesson

Testing for Matches with test()

Using the test() method to check if a pattern exists in a string, returning true or false.

Testing for Matches with test()

You'll learn how to check whether a pattern exists in a string using the test() method, which returns a simple true or false answer.

What test() Does

The test() method is your yes-or-no detector for regular expressions. You call it on a regex pattern and pass it a string to search. It returns true if the pattern is found anywhere in the string, and false if it's not.

Think of test() like a security guard checking IDs at a club entrance. The guard doesn't care where on the ID the birthdate appears or how many times it's printed—they just need to know: "Does this ID contain a valid birthdate format?" Yes or no.

Basic Usage

const pattern = /hello/;
const text1 = "hello world";
const text2 = "goodbye world";

console.log(pattern.test(text1)); // true
console.log(pattern.test(text2)); // false

The regex /hello/ checks if the word "hello" exists in the string. It finds it in text1, so test() returns true. It doesn't find it in text2, so it returns false.

Why test() Matters

This method is perfect when you only need a boolean answer—no fancy capture groups or match details, just "is this pattern present?" It's commonly used for validation:

const hasDigit = /\d/;
const password1 = "secret123";
const password2 = "secretword";

console.log(hasDigit.test(password1)); // true (contains digits)
console.log(hasDigit.test(password2)); // false (no digits)

Key Takeaway: Use test() when you need a quick true/false check for whether a regex pattern exists anywhere in a string—it's the simplest way to validate patterns.