JavaScript compile() Method

The JavaScript compile() method is used for compiling a regular expression during script execution. It deprecated in JavaScript version 1.5.

Following is the code for JavaScript compile() method −


 Live Demo

<!DOCTYPE html>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
<h1>compile() Method</h1>
<p class="sample">
That man won the race and the woman over there came second
<h3>After compile()</h3>
<p class="result"></p>
<button class="Btn">Click Here</button>
<h3>Click the above button to use compile the regex to make changes</h3>
   let sampleEle = document.querySelector(".sample");
   let result = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      var str = sampleEle.innerHTML;
      var pattern = /man/g;
      var str2 = str.replace(pattern, "person");
      result.innerHTML = str2 + "<br>";
      pattern = /(wo)?man/g;
      str2 = str.replace(pattern, "person");
      result.innerHTML += str2;


On clicking the “Click Here” button −