RegExp.compile() (Method)

Recompile a regular expression object's search mechanics.

Availability:

JavaScript - 1.2
JScript - 3.0
Internet Explorer - 4.0
Netscape - 4.0
Netscape Enterprise Server - 3.0
Opera 5.0
JavaScript syntax:-myRegExp.compile(aPattern)
-myRegExp.compile(aPattern, someAttribs)
Argument list:aPatternA regular expression-matching pattern contained in a string
someAttribsA string containing the regular expression attributes

This takes the same argument as the constructor and can be used to recycle an existing RegExp object with a freshly initialized search pattern and attributes.

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 backslashes to remain in the regular expression pattern, they will need to be double escaped. For example, this pattern:

/\d+/

Must be escaped like this when used in a string:

"\\d+"

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:

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

The regular expression compile() method is useful for those occasions when you cannot easily predict what string you will need to match. As is the case with the constructor you can define the pattern based on a user-specified value. With the compile() method, you can replace the pattern as needed without destroying and recreating the object again.

Calling the compile() method on a RegExp object is a good way to gain some performance improvements if the regular expression is used frequently during a session. It will need compiling again each time it is instantiated.