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

Phương pháp kiểm tra JavaScript RegExp ()

Phương thức RegExp test () được sử dụng để kiểm tra xem có sự trùng khớp xảy ra trong một chuỗi hay không. Nếu kết quả khớp xảy ra thì nó trả về true, ngược lại là false.

Sau đây là mã cho phương thức RegExp test () -

Ví dụ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
   font-size: 20px;
   font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript RegExp test() method</h1>
<div class="sample">The quick brown fox jumps over the lazy dog</div>
<button class="Btn">CLICK HERE</button>
<div class="result"></div>
<h3>Click on the above button to check if the above string contains 'fox'.</h3>
<script>
let fillEle = document.querySelector(".sample");
let result = document.querySelector(".result");
let regex = new RegExp("fox");
let regResult = regex.test(fillEle.innerHTML);
document.querySelector(".Btn").addEventListener("click", () => {
   if (regResult) result.innerHTML = "The above string contains fox";
   else result.innerHTML = "The above string doesn't contain fox";
});
</script>
</body>
</html>

Đầu ra

Phương pháp kiểm tra JavaScript RegExp ()

Khi nhấp vào nút “BẤM VÀO ĐÂY” -

Phương pháp kiểm tra JavaScript RegExp ()