The compile() Method in JavaScript is used to compile the regular expression while executing of script i.e compile the regular expression. It is also used to recompile and change the regular expression.
Syntax:
RegExpObject.compile(RegExp, modifier)
Where RexExp refers to the regular expression and modifier is used to specify the type of matching.
Example : This example changes the initial string and then again changes it on using compile() method.
<!DOCTYPE html> <html> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2> compile() Method </h2> <p> String: GeeksforGeeks is the computer science portal for geeks. </p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <p id="app1"></p> <script> function geek() { var str = "GeeksforGeeks is the computer" + " science portal for geeks."; var patt = /geek/g; var str2 = str.replace(patt, "GFG"); document.getElementById("app").innerHTML = " <b>Initial:</b> " + str2; patt = /(Geeks)/gi; patt.compile(patt); str2 = str.replace(patt, "GEEKS"); document.getElementById("app1").innerHTML = " <b>After using compile():</b> " + str2; } </script> </body> </html> |
Output:
Before clicking the button:

After clicking the button:

Supported Browsers: The browsers supported by JavaScript compile() Method are listed below:
- Google Chrome
- Apple Safari
- Mozilla Firefox
- Opera
- Internet Explorer


