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

Lookbehind Assertions ใน JavaScript Regular Expressions

Lookbehind Assertions ช่วยให้จับคู่รูปแบบได้ก็ต่อเมื่อมีรูปแบบที่กำหนดอยู่ก่อนหน้า โดยไม่รวมตัวที่มาก่อนหน้าเข้าไปในผลลัพธ์

ตัวอย่าง

ตัวอย่างการดึงราคาโต๊ะที่ขึ้นต้นด้วยเครื่องหมาย $:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Lookbehind Assertions 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>Lookbehind Assertions Regular Expressions</h1>
  <div class="sample">The price for 4 tables are $50 , $99 , $121 and $150.</div>
  <div style="color: green;" class="result"></div>
  <button class="btn">CLICK HERE</button>
  <h3> Click on the above button to extract the table price using lookbehind </h3>
  <script>
    let sampleEle = document.querySelector(".sample").innerHTML;
    let btnEle = document.querySelector(".btn");
    let resEle = document.querySelector(".result");
    const priceRegex = /(?<=\$)\d+/g;
    btnEle.addEventListener("click", () => {
      const matches = sampleEle.match(priceRegex);
      resEle.innerHTML = "Table price are = " + (matches ? matches.join(", ") : "Not found");
    });
  </script>
</body>
</html>

คำอธิบาย

  • /(?<=\$)\d+/g: Positive Lookbehind - จับคู่ตัวเลข (\d+) ก็ต่อเมื่อมีเครื่องหมาย $ อยู่ก่อนหน้า
  • ผลลัพธ์จะได้แค่ตัวเลข 50, 99, 121, 150 โดยไม่รวมเครื่องหมาย $
  • มีอีกแบบคือ Negative Lookbehind: (?<!\$)\d+ จับคู่ตัวเลขที่ ไม่มี $ นำหน้า

ผลลัพธ์

ก่อนกดปุ่ม: แสดงข้อความต้นฉบับ | หลังกดปุ่ม: แสดง "Table price are = 50, 99, 121, 150"