Syntax of Regular Expression
The simplest way is enclosing the expression between slashes as shown below:
Using Constructor function RegExp():
The other way of creating a regular expression is by using the constructor function “RegExp()” as shown below:
How to Create a Regular Expression?
Methods for Regular Expressions
Regular expressions are used for various purposes such as matching two strings, matching particular words in a string, searching for a particular word in strings, and replacing within a string. All of these have separate methods that can be used on the regular expression. Let’s see them one by one with example:
This method is used to match strings and as a result it returns the boolean value of true or false. Using this method, the user can verify if the particular string contains the match of a regular expression. Below is an example of two strings to show you the working of this method with regular expression:
let check = regexp.test('hello world');
let check = regexp.test('hi world');
Another method that is used with the regular expression is match() methods that check a string and return an array of all the matches, in case no match found null is returned. Below is an example for the method match() along with the flag g which is a global flag that we will see in the article, it helps searching for all the matches in the string:
let check = console.log(regexp.match(/come/g));
Another useful method is the search() method in which we pass the value that needs to be searched in the string and when found the index of that word is returned as an output:
let check = console.log(regexp.search("there"));
replace() method is used to replace a specific value in the string. It takes in two parameter and searches the string with first parameter, when found replace it with the value to be replaced:
let check = console.log(regexp.replace("there", "you"));
To make searching more precise and accurate, regular expressions use flags along with the regular expression.
There are various flags present that change the behavior of searching, some of which are described below along with examples for better understanding.
(i) ignore flag
Many times when a user performs a search, it doesn’t provide accurate results for “hi” vs “Hi”, due to it being case sensitive. For this purpose the “i” ignore flag is used to ignore the cases and makes searching easier.
let check = regexp.test('Hello there');
console.log(check); // true
(g) global flag
Mostly when using the method match() to search for a particular match in a string, it returns only the first match. But, with the use of the “g” global flag along with the method, it searches for all the matches in the string and returns an array of the matches found.
let check = console.log(regexp.match(/cook/g));
You can also use two flags together for a better result as shown below in this example:
City: New York`;
console.log( regexp.match(/a/gi) );