Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

กลุ่มการจับคู่ที่มีชื่อ (Named Capture Groups) ใน Regular Expressions ของ JavaScript

ใน JavaScript คุณสามารถจัดกลุ่มส่วนหนึ่งของ Regular Expression ได้โดยการห่อหุ้มอักขระด้วยวงเล็บ ซึ่งช่วยให้สามารถอ้างอิงกลุ่มที่จับคู่ได้ในภายหลัง

ตัวอย่าง

ตัวอย่างต่อไปนี้แสดงการใช้ Named Capture Groups เพื่อดึงปีจากข้อความ:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Named Capture Groups Example</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .sample, .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Named Capture Groups Regular Expressions</h1>
  <div class="sample">The year in which i passed school was 2012.</div>
  <div style="color: green;" class="result"></div>
  <button class="btn">CLICK HERE</button>
  <h3> Click on the above button to extract the year using named groups </h3>
  <script>
    let sampleEle = document.querySelector(".sample").innerHTML;
    let btnEle = document.querySelector(".btn");
    let resEle = document.querySelector(".result");
    const yearRegex = /(?<year>\d{4})/g;
    btnEle.addEventListener("click", () => {
      const match = sampleEle.match(yearRegex);
      resEle.innerHTML = "The year = " + (match ? match[0] : "Not found");
    });
  </script>
</body>
</html>

คำอธิบายโค้ด

  • /(?<year>\d{4})/g: Regular Expression ที่ใช้ Named Capture Group ชื่อ year เพื่อจับคู่ตัวเลข 4 หลัก
  • sampleEle.match(yearRegex): คืนค่า Array ของผลลัพธ์ที่จับคู่ได้
  • เมื่อคลิกปุ่ม จะแสดงปีที่พบใน element result

ผลลัพธ์

โค้ดจะแสดงข้อความต้นฉบับ และเมื่อกดปุ่ม "CLICK HERE" จะแสดงปีที่ดึงมาได้ (2012)