Hey dear readers!
In the introduction part, you've been familiar with the basic syntax of
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 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:
A simple example is given below.
let codingIsHiding = "Somewhere coding is hiding in this text."; let codingRegex = /coding/; let result = codingRegex.test(codingIsHiding); console.log(result); //output: true
The output of this example is true as the regex coding is present in the given string.
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
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
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.