Computer >> Máy Tính >  >> Lập trình >> Javascript

Phương thức biên dịch JavaScript ()

Phương thức biên dịch JavaScript () được sử dụng để biên dịch một biểu thức chính quy trong quá trình thực thi tập lệnh. Nó không được dùng nữa trong JavaScript phiên bản 1.5.

Sau đây là mã cho phương thức biên dịch JavaScript () -

Ví dụ

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>compile() Method</h1>
<p class="sample">
That man won the race and the woman over there came second
</p>
<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>
<script>
   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;
      pattern.compile(pattern);
      str2 = str.replace(pattern, "person");
      result.innerHTML += str2;
   });
</script>
</body>
</html>

Đầu ra

Phương thức biên dịch JavaScript ()

Khi nhấp vào nút “Nhấp vào đây” -

Phương thức biên dịch JavaScript ()