UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ RegExp/ RegExp() constructor

The RegExp() constructor creates RegExp objects.

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

Syntax

new RegExp(pattern)
new RegExp(pattern, flags)
RegExp(pattern)
RegExp(pattern, flags)

Note: RegExp() can be called with or without new, but sometimes with different effects. See Return value.

Parameters

Return value

RegExp(pattern) returns pattern directly if all of the following are true:

In all other cases, calling RegExp() with or without new both create a new RegExp object. If pattern is a regex, the new object's source is pattern.source; otherwise, its source is pattern coerced to a string. If the flags parameter is not undefined, the new object's flags is the parameter's value; otherwise, its flags is pattern.flags (if pattern is a regex).

Exceptions

Examples

Literal notation and constructor

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

The following three expressions create the same regular expression:

/ab+c/i;
new RegExp(/ab+c/, "i"); // literal notation
new RegExp("ab+c", "i"); // constructor

Before regular expressions can be used, they have to be compiled. This process allows them to perform matches more efficiently. There are two ways to compile and get a RegExp object.

The literal notation results in compilation of the regular expression when the expression is evaluated. On the other hand, the constructor of the RegExp object, new RegExp('ab+c'), results in runtime compilation of the regular expression.

Use a string as the first argument to the RegExp() constructor when you want to build the regular expression from dynamic input.

Building a regular expression from dynamic inputs

const breakfasts = ["bacon", "eggs", "oatmeal", "toast", "cereal"];
const order = "Let me get some bacon and eggs, please";

order.match(new RegExp(`\\b(${breakfasts.join("|")})\\b`, "g"));
// Returns ['bacon', 'eggs']

Specifications

Browser compatibility

See also