compile Method (Regular Expression) (JavaScript)

Compiles a regular expression into an internal format for faster execution.

rgExp.compile(pattern, [flags])

rgExp

Required. An instance of a Regular Expression object. Can be a variable name or a literal.

pattern

Required. A string expression containing a regular expression pattern to be compiled

flags

Optional. Available flags, which may be combined, are:

  • g (global search for all occurrences of pattern)

  • i (ignore case)

  • m (multiline search)

The compile method converts pattern into an internal format for faster execution. This allows for more efficient use of regular expressions in loops, for example. A compiled regular expression speeds things up when reusing the same expression repeatedly. No advantage is gained, however, if the regular expression changes.

The following example illustrates the use of the compile method:

function CompileDemo(){
   var rs;
   var s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp"
   // Create regular expression for uppercase only.
   var r = new RegExp("[A-Z]", "g");
   var a1 = s.match(r)              // Find matches.
   // Compile the regular expression for lowercase only.
   r.compile("[a-z]", "g");
// Find matches.
   var a2 = s.match(r)              
   return(a1 + "\n" + a2);
}

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). See Version Information.

Applies To: Regular Expression Object (JavaScript)

Show:
© 2014 Microsoft