DEV Community

Swarnali Roy
Swarnali Roy

Posted on • Updated on

Part 2 : Search a REGEX with .test() Method

Hey dear readers!
Welcome to another part of the JavaScript Regular Expressions series.
In the introduction part, you've been familiar with the basic syntax of Regular Expressions.

In this part, we will know How to Search a REGEX in a String

The most commonly used method to search is the .test() method. Let's get started with that. 👇🏻

.test() method to search a regex in a string

The .test() method takes the regex, applies it to a string (which is placed inside the parentheses), and returns true if your pattern finds something similar to the given regex and false otherwise.

The basic syntax for this method is: regex.test(string)
A simple example is given below.

let codingIsHiding = "Somewhere coding is hiding in this text.";
let codingRegex = /coding/; 
let result = codingRegex.test(codingIsHiding);

//output: true
Enter fullscreen mode Exit fullscreen mode

The output of this example is true as the regex coding is present in the given string.

Search a String with Multiple Possibilities with .test()

Sometimes, we need to search for different possibilities in a single string. Instead of creating so many different regex, we can search for multiple patterns using the alternation or OR operator: |.

let myString = "Swarnali loves rain and snow.";
let weather = /rain|cloud|sun|snow|heat/ ;
let pet = /cats|dogs|birds|fishes/

let weatherResult = weather.test(myString);
let petResult = pet.test(myString);

console.log(weatherResult); //output: true
console.log(petResult); //output: false
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, both the weather regex and pet regex have multiple possibilities to be true for the string. The string contains two possibilities of the weather regex: rain and snow but does not contain any of the possibilities written in the pet regex.
So, the first console.log() will return true and the second one will return false for the given string.

In this part, we learnt about searching a regex in a string with single and multiple possibilities with .test() method. In the next part, we will learn another method to search and extract a match from the string.

Top comments (2)

truepadawan profile image

thanks, i just looked into REGEX in python and C++ a few days ago

swarnaliroy94 profile image
Swarnali Roy

I'll add more parts gradually. Keep following. Thank you