Javascript - RegExp constructor argument

Introduction

Regular expressions can be created via the RegExp constructor.

It accepts two arguments: a string pattern and an optional string of flags.

Any regular expression that can be defined using literal syntax can be defined using the constructor:

The following Regular expressions match the first instance of "bat" or "cat", regardless of case.

var pattern1 = /[bc]at/i;

Same as pattern1, using the constructor.

var pattern2 = new RegExp("[bc]at", "i");

Since the argument of the RegExp constructor is a string, you need to escape characters.

All metacharacters must be double-escaped, \\ becomes \\\\ when used in a regular-expression string.

Demo

var re = null,
    i;/*from   www.  ja  v  a  2 s .c o  m*/

re = new RegExp("cat", "g");
console.log(re.test("catastrophe"));

Result