How do you create a new RegExp object in JavaScript?

Regular expressions are a powerful tool for searching and manipulating text in JavaScript. To create a new RegExp object in JavaScript, you can use either the constructor function or the regular expression literal notation.

Using the Constructor Function

To create a new RegExp object using the constructor function, you can pass a regular expression pattern as a string, along with any optional flags, to the RegExp constructor.

For example, the following code creates a new RegExp object that matches any string containing the word "hello", case-insensitive:

const pattern = "hello";
const flags = "i"; // i flag for case-insensitive matching
const regex = new RegExp(pattern, flags);

You can also create a RegExp object without any flags, like this:

const pattern = "\\d+"; // a pattern that matches one or more digits
const regex = new RegExp(pattern);

Note that because backslashes are used to escape special characters in regular expression patterns, you need to double-escape them in JavaScript strings.

Using the Regular Expression Literal Notation

You can also create a new RegExp object using the regular expression literal notation, which uses forward slashes to delimit the regular expression pattern and any optional flags.

For example, the following code creates the same regular expression as the previous example, using the literal notation:

const regex = /\d+/;

Note that you don’t need to escape special characters in regular expression patterns when using the literal notation.

Common flags

Flags are used to modify the behavior of a regular expression. Here are some commonly used flags in JavaScript:

You can specify flags as an optional second argument to the RegExp constructor, or by appending them to the end of a regular expression literal.

// Using the constructor function with flags
const regex = new RegExp("\\d+", "g"); // matches all digits

// Using the literal notation with flags
const regex = /\d+/g; // also matches all digits

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: