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

Kiểm tra và thực thi Regex trong JavaScript: test() vs exec()

JavaScript cung cấp 2 phương thức chính trên đối tượng RegExp để kiểm tra và trích xuất khớp:

1. regex.test(str) - Kiểm tra có khớp không

  • Trả về true/false
  • Nhanh, chỉ cần biết có/không
  • Với flag g: cập nhật lastIndex, có thể dùng lặp

2. regex.exec(str) - Thực thi và lấy kết quả chi tiết

  • Trả về Array (match đầu tiên) hoặc null
  • Array có: [0] = full match, [1]... = capture groups, .index, .input, .groups (named groups)
  • Với flag g: gọi nhiều lần để lấy tất cả matches

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Test và Exec Regex JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; margin: 10px 0; }
    button { padding: 8px 16px; cursor: pointer; }
    pre { background: #f5f5f5; padding: 10px; overflow: auto; }
  </style>
</head>
<body>
  <h1>Test và Exec Regular Expression</h1>
  <div class="sample" id="sample"></div>
  <div style="color: green;" class="result" id="result"></div>
  <button class="Btn" id="btn">NHẤN VÀO ĐÂY</button>
  <h3> Nhấn nút để test và exec regex trên chuỗi </h3>
  <script>
    const sampleEle = document.querySelector('#sample');
    const resEle = document.querySelector('#result');
    const str = 'Hello world. This is a beautiful world';
    sampleEle.innerHTML = `Chuỗi: "${str}"`;
    
    // Regex: tìm "world" (không có flag g)
    const pattern = new RegExp("world");
    
    document.querySelector("#btn").addEventListener("click", () => {
      // test() - chỉ kiểm tra
      const testResult = pattern.test(str);
      resEle.innerHTML = `pattern.test(str) = ${testResult}
`; // exec() - lấy chi tiết const execResult = pattern.exec(str); if (execResult) { resEle.innerHTML += `pattern.exec(str) = [${execResult}]
`; resEle.innerHTML += ` - Full match: "${execResult[0]}"
`; resEle.innerHTML += ` - Index: ${execResult.index}
`; resEle.innerHTML += ` - Input: "${execResult.input}"
`; } else { resEle.innerHTML += `pattern.exec(str) = null
`; } // Demo với flag g (global) resEle.innerHTML += "
--- Với flag 'g' ---
"; const globalPattern = /world/g; let match; let count = 0; while ((match = globalPattern.exec(str)) !== null) { count++; resEle.innerHTML += `Match ${count}: "${match[0]}" tại index ${match.index}
`; } resEle.innerHTML += `Tổng: ${count} matches
`; resEle.innerHTML += `lastIndex cuối: ${globalPattern.lastIndex}`; }); </script> </body> </html>

Kết quả

pattern.test(str) = true
pattern.exec(str) = [world]
  - Full match: "world"
  - Index: 6
  - Input: "Hello world. This is a beautiful world"

--- Với flag 'g' ---
Match 1: "world" tại index 6
Match 2: "world" tại index 33
Tổng: 2 matches
lastIndex cuối: 0

So sánh nhanh:

Đặc điểmtest()exec()
Trả vềBooleanArray / null
Thông tin chi tiếtKhôngCó (index, groups, input...)
Hiệu năngNhanh hơnChậm hơn
Dùng khiChỉ cần true/falseCần vị trí, groups, nhiều match

String methods tương đương:

  • str.match(regex) ~ regex.exec(str) (nhưng behavior khác với flag g)
  • str.search(regex) ~ regex.test(str) (trả về index)
  • str.matchAll(regex) (ES2018) - trả về iterator tất cả matches (cần flag g)

⚠️ Cạm bẫy lastIndex với flag g:

const regex = /world/g;
regex.test("world"); // true, lastIndex = 5
regex.test("world"); // false! lastIndex = 5, tìm từ index 5
// Cần reset: regex.lastIndex = 0;