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

Công dụng của phương thức test() trong JavaScript


test() là phương thức biểu thức chính quy (regular expression). Tìm kiếm chuỗi theo mẫu, trả về true hoặc false tùy kết quả. Gặp mẫu trả true, không thì false. Phân biệt chữ hoa thường (case sensitive).

Ví dụ 1

Văn bản "Tutorix is the best e-learning platform", mẫu "Tu" có mặt nên test() trả true.

<html> <body> <p id="text">Tutorix is the best e-learning platform</p> <p id="test"></p> <script> 
    var text = document.getElementById("text").innerHTML; 
    document.getElementById("test").innerHTML = /Tu/.test(text); 
</script> </body> </html>

Kết quả

Tutorix is the best e-learning platform true

Ví dụ 2

Mẫu "tu" (thường) kiểm tra. Văn bản có "Tu" (hoa) nhưng không có "tu". test() kiểm tra case sensitivity, kết quả false.

<html> <body> <p id="text">Tutorix is the best e-learning platform</p> <p id="test"></p> <script> 
    var text = document.getElementById("text").innerHTML; 
    document.getElementById("test").innerHTML = /tu/.test(text); 
</script> </body> </html>

Kết quả

Tutorix is the best e-learning platform false