JavaScript | compile() Method

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:
Before clicking the button:
compile
After clicking the button:
compile



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


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mayank5326



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.