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

Regular Expression Modifiers (Flags) ใน JavaScript

Flags (Modifiers) คือ ตัวเลือกเสริมของ Regex วางหลัง /pattern/flags หรือใน Constructor new RegExp('pattern', 'flags')

Flagชื่อคำอธิบาย
gGlobalหา Match ทั้งหมด ไม่หยุดที่ตัวแรก
iCase-Insensitiveไม่สนใจพิมพ์ใหญ่/เล็ก
mMultiline^ $ จับคู่ต้น/ท้ายบรรทัด (ไม่ใช่ทั้ง String)
sDotAll (ES2018). จับคู่ Newline ด้วย
uUnicodeรองรับ Unicode Property Escapes, Surrogate Pairs
yStickyจับคู่ที่ Index ปัจจุบันเท่านั้น (lastIndex)

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Regex Modifiers</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>JavaScript Regular Expression Modifiers</h1>
  <div class="sample"></div>
  <div style="color: green;" class="result"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to see modifiers on the string </h3>
  <script>
    let sampleEle = document.querySelector('.sample');
    let resEle = document.querySelector('.result');
    let str = '\nHello world. This is a beautiful world';
    sampleEle.innerHTML = str;
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML += '/^Hello/m = ' + str.match(/^Hello/m) + '<br>';
      resEle.innerHTML += '/world/g = ' + str.match(/world/g) + '<br>';
      resEle.innerHTML += '/WORLD/i = ' + str.match(/WORLD/i) + '<br>';
    });
  </script>
</body>
</html>

คำอธิบายตัวอย่าง

  • /^Hello/m: Multiline - ^ จับคู่ต้นบรรทัดที่ 2 (หลัง \n) → Match
  • /world/g: Global - หา "world" ทั้ง 2 ตำแหน่ง → ["world", "world"]
  • /WORLD/i: Case-Insensitive - จับคู่ "world" แบบไม่สนใจ Case → ["world"]

ผลลัพธ์

แสดงผลลัพธ์ของแต่ละ Flag แบบแยกบรรทัด