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

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials