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

Trích xuất từ trong dấu ngoặc kép bằng Regex (JavaScript)


Regex /"(.*?)"/g khớp nội dung trong dấu ngoặc kép kép. .*? non-greedy (khớp ít nhất). exec() lặp để lấy tất cả matches.

Ví dụ

Trích xuất "World" từ chuỗi Hello "World":

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Extract quoted words</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: red; }
  </style>
</head>
<body>
  <h1>Trích xuất từ trong dấu ngoặc kép</h1>
  <div class="result">Hello "World"</div>
  <div class="sample"></div>
  <button class="Btn">TRÍCH XUẤT</button>
  <h3>Nhấn nút để lấy text giữa dấu ngoặc kép</h3>
  <script>
    const resEle = document.querySelector(".result");
    const sampleEle = document.querySelector(".sample");
    const btn = document.querySelector(".Btn");
    const regex = /"(.*?)"/g;
    btn.addEventListener("click", () => {
      let match;
      while ((match = regex.exec(resEle.textContent)) !== null) {
        sampleEle.innerHTML += `Tìm thấy: ${match[1]}<br>`; // match[1] là group 1
      }
    });
  </script>
</body>
</html>

Kết quả

Hiển thị: Tìm thấy: World.

Cải tiến: Dùng str.matchAll(regex) (ES2020) để lấy iterator tất cả matches dễ dàng hơn.