Creating a RegExp Object


In JavaScript, regular expressions are encapsulated by the RegExp class. You can create RegExp objects either by using

  1. Using the literal syntax
  2. The RegExp constructor

Regular expression literals are specified as a series of characters within a pair of forward slashes (/), for example, /abc/. The content between the slashes is the pattern to be matched. The above pattern matches the string ‘abc’. The below code creates a RegExp object and assigns it to the variable ‘dwords‘. The pattern ‘/d[a-zA-Z]*d/‘ defines all words that start and end with the letter ‘d’ like did, deed, dud, duped, doomed etc.

let dwords = /d[a-zA-Z]*d/;

The literal regex syntax is similar to the literal syntax for strings where you enclose the characters that make up the string within single quotes (‘) or double quotes(“).

let singleQuotesEx = 'This is an example string literal in single quotes';
let doubleQuotesEx = "This is an example string literal in double quotes";

You can specify flags after the second slash.

let dwords = /d[a-zA-Z]*d/i;

The flag ‘i’ stands for ignorecase which says that the case of the matched text does not matter which means valid matches are Did, DiD, DID, doomed, doOMeD etc. The above RegExp object could also be created using the RegExp constructor. You pass the pattern to be matched as a string parameter to the RegExp constructor.

let dwords = new RegExp("d[a-zA-Z]*d");

The constructor can also take a second string parameter where you can specify the flags. We will explore regular expression flags in more detail later.

let dwords = new RegExp("d[a-zA-Z]*d", "i");

Let us try to unerstand the pattern though we will study them in detail later. The first ‘d’ matches the the letter ‘d’ literally. It says the matching string must start with a ‘d’. So is the case with the second ‘d’. The square brackets ‘[ ]‘ specify a character class. The ‘a-z‘ means any lowercase alphabet from a to z, and ‘A-Z‘ means any uppercase alphabet. The asterisk indicates the previous element (the square brackets and the stuff inside it) is repeated 0 or more times.