JavaScript RegExp compile()
Syntax & Examples

RegExp.compile() method

The compile() method of the RegExp object in JavaScript (re-)compiles a regular expression during execution of a script. This method is non-standard and not recommended for use in production.


Syntax of RegExp.compile()

The syntax of RegExp.compile() method is:

compile(pattern, flags)

This compile() method of RegExp (Re-)compiles a regular expression during execution of a script. This method is non-standard and may not be supported across all browsers.

Parameters

ParameterOptional/RequiredDescription
patternrequiredA string that contains the text of the regular expression.
flagsoptionalA string containing any combination of 'g', 'i', 'm', 'u', 'y', and 's' to specify global, case-insensitive, multiline, Unicode, sticky, and dotAll matching modes.

Return Type

RegExp.compile() returns value of type RegExp.



✐ Examples

1 Using compile() to change the pattern of a RegExp

In JavaScript, we can use the compile() method to change the pattern of an existing RegExp object.

For example,

  1. We create a RegExp object regex with the pattern /abc/.
  2. We use the compile() method to change the pattern of regex to /xyz/.
  3. We test the new pattern on the string 'xyz' and log the result to the console.

JavaScript Program

let regex = /abc/;
regex.compile('xyz');
console.log(regex.test('xyz'));

Output

true

2 Using compile() to add flags to a RegExp

In JavaScript, we can use the compile() method to add flags to an existing RegExp object.

For example,

  1. We create a RegExp object regex with the pattern /abc/.
  2. We use the compile() method to add the 'i' flag for case-insensitive matching.
  3. We test the modified pattern on the string 'ABC' and log the result to the console.

JavaScript Program

let regex = /abc/;
regex.compile('abc', 'i');
console.log(regex.test('ABC'));

Output

true

3 Using compile() to change both pattern and flags of a RegExp

In JavaScript, we can use the compile() method to change both the pattern and flags of an existing RegExp object.

For example,

  1. We create a RegExp object regex with the pattern /abc/.
  2. We use the compile() method to change the pattern to /xyz/ and add the 'g' flag for global matching.
  3. We test the modified pattern on the string 'xyz xyz' and log the result to the console.

JavaScript Program

let regex = /abc/;
regex.compile('xyz', 'g');
console.log(regex.test('xyz xyz'));

Output

true

Summary

In this JavaScript tutorial, we learned about compile() method of RegExp: the syntax and few working examples with output and detailed explanation for each example.