0
0
JavascriptHow-ToBeginner · 3 min read

How to Use test() Method in JavaScript Regex

In JavaScript, use the test() method on a regular expression object to check if a pattern exists in a string. It returns true if the pattern matches and false otherwise.
📐

Syntax

The test() method is called on a regular expression object and takes a string as input. It returns a boolean indicating if the pattern matches anywhere in the string.

  • regex: The regular expression object.
  • string: The text to test against the regex.
  • Returns true if the pattern is found, otherwise false.
javascript
regex.test(string)
💻

Example

This example shows how to check if the word "hello" exists in a string using test(). It prints true if found, otherwise false.

javascript
const regex = /hello/;
const text1 = "hello world";
const text2 = "goodbye world";

console.log(regex.test(text1)); // true
console.log(regex.test(text2)); // false
Output
true false
⚠️

Common Pitfalls

One common mistake is using the test() method with a global /g flag on the regex. This causes test() to remember the last index and can give unexpected results on repeated calls.

Always avoid the /g flag when using test() or reset the regex lastIndex manually.

javascript
const regex = /hello/g;
const text = "hello hello";

console.log(regex.test(text)); // true
console.log(regex.test(text)); // false (unexpected)

// Correct way without /g flag
const regex2 = /hello/;
console.log(regex2.test(text)); // true
console.log(regex2.test(text)); // true
Output
true false true true
📊

Quick Reference

UsageDescription
regex.test(string)Returns true if regex matches string, else false
/pattern/.test(text)Checks if 'pattern' exists in 'text'
Avoid /g flag with test()Global flag causes stateful behavior and bugs
Returns booleanUse in if conditions or logical checks

Key Takeaways

Use regex.test(string) to check if a pattern exists in a string and get a true/false result.
Do not use the global /g flag with test() to avoid unexpected false results on repeated calls.
test() returns a boolean and is useful for simple pattern presence checks.
Call test() directly on a regex object with the string you want to check.
Remember test() only tells if a match exists, not what or where it is.