Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức compile() trong JavaScript (Đã lỗi thời)

Phương thức compile() dùng để compile lại biểu thức chính quy (regex) trong quá trình chạy script. Đã bị deprecated từ JavaScript 1.5.

Ví dụ

<!DOCTYPE html> <html> <head> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    } </style> </head> <body> <h1>Phương thức compile() (Deprecated)</h1> <p class="sample"> That man won the race and the woman over there came second </p> <h3>Sau khi dùng compile()</h3> <p class="result"></p> <button class="Btn">Nhấn vào đây</button> <h3>Nhấn nút để compile regex và thay thế</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); // deprecated       str2 = str.replace(pattern, "person");       result.innerHTML += str2;    }); </script> </body> </html>

Kết quả

Thay thế "man" thành "person", sau đó dùng compile() để thay "woman" cũng thành "person".

Lưu ý: compile() đã lỗi thời, không nên dùng trong code hiện đại.