This content originally appeared on DEV Community and was authored by Swarnali Roy
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: 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.
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.
This content originally appeared on DEV Community and was authored by Swarnali Roy
Swarnali Roy | Sciencx (2021-07-24T22:24:49+00:00) Part 2 : Search a REGEX with .test() Method. Retrieved from https://www.scien.cx/2021/07/24/part-2-search-a-regex-with-test-method/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.