Course contentsShow
← JavaScript
Lesson 163 of 2,7235. StringsFree lesson

test() on RegExp Objects

Learn how to use the RegExp.test() method to check if a pattern exists in a string.

test() on RegExp Objects

What You'll Learn

You'll learn how to use the test() method on RegExp objects to quickly check whether a pattern exists in a string, returning a simple true or false.

The Core Idea

The test() method is a powerful tool that lives on RegExp objects (not strings!). While match() and search() are string methods that work with regular expressions, test() belongs to the RegExp object itself. It answers one simple question: "Does this pattern exist in the string?" The answer is always true or false.

Think of test() like a security scanner at an airport. It doesn't care where the item is in your bag or how many times it appears—it just tells you "yes, found it" or "no, not present."

How to Use test()

You create a RegExp pattern first, then call test() on it, passing the string you want to check:

const pattern = /hello/;
const result = pattern.test("hello world");
console.log(result); // true

You can also use it inline:

console.log(/cat/.test("I have a cat")); // true
console.log(/dog/.test("I have a cat")); // false

The method is case-sensitive by default:

console.log(/Hello/.test("hello world")); // false

Why Use test() Instead of search()?

When you only need a yes/no answer and don't care about the position or the actual match, test() is clearer and more expressive. It makes your intent obvious: you're testing for existence, not searching for a location.

Key Takeaway: The test() method on RegExp objects returns true if the pattern is found in a string and false if it's not—perfect for simple existence checks.