JS: RegExp Constructor

By Xah Lee. Date: . Last updated: .

To create a instance of RegExp object , there are 2 ways:

  1. /pattern/flags → literal expression for regexp.
  2. new RegExp("pattern", "flags") → Regexp constructor. Useful for converting a string into regexp object.

[see JS: RegExp Object]

RegExp Constructor

For the syntax and meaning of pattern and flag, see JS: RegExp Syntax

Note: when using RegExp(pattern), you need to use double backslash in the pattern string for any single backslash in your regex. Because, single backslash is used in string to escape the next character. So, when you use double backslash, the RegExp will just get a single backslash.

// remember to double backslash when using RegExp constructor

const rx1 = new RegExp("\\d+"); // one or more digit
console.log(rx1.test("333")); // true. match found

const rx2 = new RegExp("\d+"); // WRONG
console.log(rx2.test("333")); // false


ECMAScript® 2016 Language Specification#sec-regexp-constructor

RegExp Topic

  1. JS: RegExp Tutorial
  2. JS: RegExp Syntax
  3. JS: Regex Find/Replace
  4. JS: RegExp Object
  5. JS: RegExp Constructor
  6. JS: RegExp.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon