Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | compile() Method

  • Last Updated : 12 Apr, 2021

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. 

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>
<body style="text-align:center">
    <h1 style="color:green">
      compile() Method
        String: GeeksforGeeks is the
      computer science portal for geeks.
    <button onclick="geek()">
        Click it!
    <p id="app"></p>
    <p id="app1"></p>
        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;
            str2 = str.replace(patt, "GEEKS");
            document.getElementById("app1").innerHTML =
                " <b>After using compile():</b> " + str2;

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 


My Personal Notes arrow_drop_up
Recommended Articles
Page :