Flags (Modifiers) คือ ตัวเลือกเสริมของ Regex วางหลัง /pattern/flags หรือใน Constructor new RegExp('pattern', 'flags')
| Flag | ชื่อ | คำอธิบาย |
|---|---|---|
g | Global | หา Match ทั้งหมด ไม่หยุดที่ตัวแรก |
i | Case-Insensitive | ไม่สนใจพิมพ์ใหญ่/เล็ก |
m | Multiline | ^ $ จับคู่ต้น/ท้ายบรรทัด (ไม่ใช่ทั้ง String) |
s | DotAll (ES2018) | . จับคู่ Newline ด้วย |
u | Unicode | รองรับ Unicode Property Escapes, Surrogate Pairs |
y | Sticky | จับคู่ที่ 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 แบบแยกบรรทัด