How to write regular expressions in JavaScript

A regular expression is a sequence of characters that are used for pattern matching; it can be used for searching and replacing text.

Note: This expression is not the property of just one particular programming language; instead, it is supported by multiple languages.

svg viewer

Regular expression patterns

Expression Description
[] Used to find any of the characters or numbers specified between the brackets.
\d Used to find any digit.
\D Used to find anything that is not a digit.
\d+ Used to find any number of digits.
x* Used to find any number (can be zero) of occurrences of x.

Creating a regular expression

A regular expression can be created with or without the constructor.

According to the official documentation JavaScript, the RegExp constructor creates a regular expression object for pattern matching.

// Using a constructor
regex1 = new RegExp("\d+");
// Without using a constructor
regex2 = '/\d+/';
// Checking the values for equality
console.log(regex1 == regex2);
// Checking the values and types of the variables
console.log(regex1 === regex2);

Using regular expressions with the test() method

The test() method searches the string for a pattern; it returns “true” upon finding a match, and “false” if otherwise.

// Find out if the sentences contains numbers.
let pattern = /\d+/;
console.log(pattern.test(`Sally is 1 year old.
Harry's phone number is 1234.`));
console.log(pattern.test("I had frozen yoghurt after lunch today"));

Using regular expressions with the exec() method

The exec() method returns an object containing the matched pattern, the index at which the pattern is first found and the input string if there is a match. If there is no match, the method returns a null object.

// Find out if the sentences contains numbers.
obj1 = /\d+/g.exec(`Sally is 1 year old.
Harry's phone number is 1234`);
console.log(obj1);
obj2 = /\d+/g.exec("I had frozen yoghurt after lunch today");
console.log(obj2);

Using regular expressions with the match() method

The match() method searches the string against the regular expression and returns the matches in an Array object. The g is a global flag used to specify that the entire string needs to be checked for matches.

// Display all the numbers in the text.
let sentence = `Sally is 1 year old.
Harry's phone number is 1234`;
let result = sentence.match(/\d+/g);
for( let i = 0; i < result.length; i++)
{
console.log(result[i]);
}
Copyright ©2024 Educative, Inc. All rights reserved