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

Lookbehind Assertions (Khẳng định nhìn về sau) trong Biểu thức chính quy JavaScript

Lookbehind Assertions cho phép khớp một mẫu chỉ khi nó được tiền tố bởi một mẫu khác, mà không bao gồm tiền tố đó trong kết quả khớp. JavaScript hỗ trợ hai loại:

  • Positive lookbehind: (?<=pattern) - khớp nếu trước đó là pattern
  • Negative lookbehind: (?<!pattern) - khớp nếu trước đó KHÔNG phải là pattern

Ví dụ minh họa

Trích xuất giá tiền (chỉ số) đi kèm ký hiệu $:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Lookbehind Assertions</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .sample, .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Lookbehind Assertions - Trích xuất giá tiền</h1>
  <div class="sample">Giá 4 bàn là $50, $99, $121 và $150.</div>
  <div style="color: green;" class="result"></div>
  <button class="btn">NHẤN VÀO ĐÂY</button>
  <h3> Nhấn nút để trích xuất giá bàn bằng lookbehind </h3>
  <script>
    const sampleEle = document.querySelector(".sample").innerHTML;
    const btnEle = document.querySelector(".btn");
    const resEle = document.querySelector(".result");
    // Positive lookbehind: chỉ lấy số đứng sau $
    const priceRegex = /(?<=\$)\d+/g;
    btnEle.addEventListener("click", () => {
      const matches = sampleEle.match(priceRegex);
      resEle.innerHTML = "Giá các bàn = " + (matches ? matches.join(", ") : "Không tìm thấy");
    });
  </script>
</body>
</html>

Kết quả

Khi nhấn nút, các giá trị 50, 99, 121, 150 sẽ được trích xuất và hiển thị, bỏ qua ký hiệu $.

Ứng dụng thực tế: Xử lý tiền tệ, phân tích log, trích xuất dữ liệu có tiền tố cố định.