RegExp() (Constructor)

A constructor function for creating new regular expression objects.


ECMAScript edition - 3
JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Opera 5.0
JavaScript syntax:-new RegExp(aPattern)
-new RegExp(aPattern, someAttribs)
Argument list:aPatternA regular expression-matching pattern contained in a string
someAttribsA string containing the regular expression attributes

A RegExp constructor is used to create a new regular expression object containing a search pattern.

The first argument is a string containing a properly escaped pattern. Because the backslash character (\) is an escape when used in a string, for the back slashes to remain in the regular expression pattern, they will need to be double escaped. For example, this pattern:


Must be escaped like this when used in a string:


The second argument is the attributes for the pattern. You should not put the attributes on the end of the pattern but specify them separately. These are available:

iIgnore caseJavaScript 1.2
gMatch globallyJavaScript 1.2
igIgnore case and match globallyJavaScript 1.2
mMultiple line parsingJavaScript 1.5

The regular expression constructor is useful for those occasions when you cannot easily predict what string you will need to match. If you could, it is likely you would use a regular expression literal. If the user is going to enter some value that determines what the search characteristics are to be then a RegExp() constructor may be useful.

Example code:

   // Declare a variable and assign a RegExp literal to it
   var myPattern = /x$/;
   // Now do the same thing with a RegExp constructor
   var myPattern = new RegExp("x$");

See also:new, RegExp literal, RegExp object, RegExp pattern - attributes, RegExp pattern - character literal, RegExp.constructor, Regular expression


ECMA 262 edition 3 - section - 15.10.4