Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 24, 2021 10:24 pm GMT

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);console.log(result); \\output: true

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: trueconsole.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.

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.

Original Link: https://dev.to/swarnaliroy94/part-2-search-a-regex-with-test-method-5606

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To