Example: var patt = /adarsh/i;
Here, adarsh is a pattern and i is a modifier(represents make search case-insensitive)
We can combine REGEX with string methods like search() and replace() to make our operations easy.
Using search(): The search() method searches a string for a specified value and returns the position of the match.
var str = "I'm Adarsh!";
var z = str.search("/adarsh/i");
Here, 4 will be stored in z as adarsh is presentin original string. Please note here we have used modifier i due to which Adarsh can search adarsh.
Using replace(): The replace() method replaces a specified value with another value in a string.
var str = "I'm Adarsh";
var z = str.replace(/adarsh/i, "Harshdeep");
Here, I'm Harshdeep will be stored in z variable.
Some of the REGEX patterns are:
var patt = /e/;
patt.test("Sun and Moon are friend");
Since there is an "e" in the string, the output of the code above will be: true
Also please note we may use let new RegExp(pattern, “modifier”) to create our own REGEX with required pattern and modifier.
Try the following example in the editor below.
You are given a string Str and a pattern Patt, you have to search Patt in Str and print true if it is present otherwise print false. Make search case insensitive.