JavaScript

Regular Expressions in JavaScript

In our daily lives we continuously browse, search and find stuff on google, sometimes we find what we’re looking for, other times we fail. To make this search more precise, accurate regular expressions are there that help users with search and replace.

Users can also use regular expressions for input validation or form fields, such as checking if the PIN entered consists of all numeric values or if it has some special characters. In JavaScript these regular expressions are objects that come as a built-in feature with the name “RegExp”. In this article we’ll discuss regular expressions in JavaScript, their syntax and how they’re used along with examples for your better understanding.

Syntax of Regular Expression

There are two ways regular expressions can be written in JavaScript

Using literal:
The simplest way is enclosing the expression between slashes as shown below:

const rE = /regularexpression/;

Using Constructor function RegExp():
The other way of creating a regular expression is by using the constructor function “RegExp()” as shown below:

const rE = new RegExp('regularexpression');

How to Create a Regular Expression?

Creating regular expressions in JavaScript is simple, you can either use slashes or the RegExp() constructor. Below are the two examples using both of these methods of creating regular expression:

let regexp = /hello there/;
console.log(regexp);

Output:

Example:

let regexp = new RegExp('hello there');
console.log(regexp);

Output:

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:

test() method
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 regexp = /hello/;
let check = regexp.test('hello world');

console.log(check);

Output:

Example:

let regexp = /hello/;
let check = regexp.test('hi world');

console.log(check);

Output:

match() method
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 regexp = "Welcome to our website";
let check = console.log(regexp.match(/come/g));

Output:

search() method
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 regexp = "Hey there, welcome!";
let check = console.log(regexp.search("there"));

Output:

replace() method
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 regexp = "Hey there, welcome!";
let check = console.log(regexp.replace("there", "you"));

Output:

Pattern Flags

To make searching more precise and accurate, regular expressions use flags along with the regular expression.

Syntax:

/regular expression/flags

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 regexp = /hello/i;
let check = regexp.test('Hello there');

console.log(check); // true

Output:

(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 regexp = "The cook was cooking cookies";
let check = console.log(regexp.match(/cook/g));

Output:

You can also use two flags together for a better result as shown below in this example:

let regexp = `Name: John
Age: 45
City: New York`;

console.log( regexp.match(/a/gi) );

Output:

Conclusion

Regular expression helps users to make searching and replacing stuff in a string or form validation easier. It’s used along with various methods and flags to find elements ignoring the case much faster and provide users with precise results. Here in this article we discussed Regular expressions in JavaScript along with their different syntax and methods, and how to make searching more accurate using flags. Examples are also provided for you to understand it better.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.