1 minute read

There are two ways to create a RegExp object: a literal notation and a constructor.

  1. Parameters for literal notation are enclosed in slashes and do not use quotation marks.
  2. Constructor function parameters are not enclosed in slashes, but use quotation marks.

The following three expressions create the same regular expression object:


let er = /ab+c/i; 
let er = new RegExp('ab+c', 'i') 
let er = new RegExp(/ab+c/, 'i') 

The literal notation results in the compilation of the regular expression when the expression is evaluated.

Use literal notation when the regular expression will remain constant.

For example, if you use literal notation to construct a regular expression used in a loop, the regular expression will not be recompiled on every iteration.

The constructor of the regular expression object, for example, new RegExp (‘ab + c’), results in the run-time compilation of the regular expression.

Use the constructor function when you know the regex pattern will change, or you don’t know the pattern and get it from another source, such as user input.

Flags

As of ECMAScript 6, new RegExp (/ ab + c /, ‘i’) no longer throws a TypeError (“you cannot supply flags when constructing a regular expression from another”) when the first argument is a RegExp and the second argument flags is present. Instead, a new RegExp is created from the arguments.

When using the constructor function, normal string escape rules (before special characters with \ when included in a string) are required.

For example, the following are equivalent:


let er = /\w+/
let er = new RegExp('\\w+')

Regular expressions may have flags that affect the search.

There are only 6 of them in JavaScript:


i
With this flag the search is case-insensitive: no difference between A and a (see the example below).
g
>With this flag the search looks for all matches, without it – only the first match is returned.
m
Multiline mode (covered in the chapter Multiline mode of anchors ^ $, flag “m”).
s
Enables “dotall” mode, that allows a dot . to match newline character \n (covered in the chapter Character classes).
u
Enables full Unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter Unicode: flag “u” and class \p{…}.
y
“Sticky” mode: searching at the exact position in the text (covered in the chapter Sticky flag “y”, searching at position)