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

วนลูปหาค่าที่ตรงกับ Regular Expression ใน JavaScript

สามารถใช้เมธอด match() ร่วมกับ Regular Expression ที่มี Flag g (Global) เพื่อหาค่าที่ตรงกับรูปแบบทั้งหมดในสตริง แล้วนำไปวนลูปประมวลผลต่อได้

ตัวอย่าง: หาคำที่ลงท้ายด้วย "at"

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loop Regex Matches</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result, .sample { font-size: 18px; font-weight: 500; }
        .sample { color: red; }
        .result { color: blueviolet; }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
    </style>
</head>
<body>
    <h1>วนลูปหาค่าที่ตรงกับ Regex</h1>
    <div class="sample">
        มีแมว (cat) นั่งข้างไม้กริกเก็ต (cricket bat) กำลังไล่หนู (rat)
    </div>
    <div class="result"></div>
    <button class="Btn">ค้นหาคำลงท้าย "at"</button>
    <h3>กดปุ่มเพื่อหาคำที่ลงท้ายด้วย "at" ในประโยคข้างต้น</h3>

    <script>
        let BtnEle = document.querySelector(".Btn");
        let resEle = document.querySelector(".result");
        let sampleEle = document.querySelector(".sample");
        
        let text = sampleEle.innerText; // ใช้ innerText เพื่อเอาเฉพาะข้อความ
        
        BtnEle.addEventListener("click", () => {
            // ใช้ match() กับ regex /at/g (หา "at" ทุกที่)
            let matches = text.match(/at/g);
            
            if (matches) {
                matches.forEach((element, index) => {
                    resEle.innerHTML += `${index + 1}. พบคำที่ลงท้าย "at" → "${element}" <br>`;
                });
                resEle.innerHTML += `<br>รวมทั้งหมด: ${matches.length} คำ`;
            } else {
                resEle.innerHTML = "ไม่พบคำที่ตรงเงื่อนไข";
            }
        });
    </script>
</body>
</html>

ผลลัพธ์

ประโยค: "มีแมว (cat) นั่งข้างไม้กริกเก็ต (cricket bat) กำลังไล่หนู (rat)"
คำที่ลงท้าย "at": cat, bat, rat (3 คำ)

วิธีการอื่นๆ ที่มีประโยชน์

1. ใช้ matchAll() (ES2020) - ได้ข้อมูลรายละเอียดมากกว่า

const regex = /(\w+)at/g;
const str = "cat bat rat";
const matches = [...str.matchAll(regex)];

matches.forEach(match => {
    console.log("Full match:", match[0]);  // cat, bat, rat
    console.log("Group 1:", match[1]);     // c, b, r
    console.log("Index:", match.index);    // ตำแหน่งในสตริง
});

2. ใช้ exec() ในลูป while (แบบดั้งเดิม)

const regex = /at/g;
const str = "cat bat rat";
let match;

while ((match = regex.exec(str)) !== null) {
    console.log("พบ:", match[0], "ที่ตำแหน่ง:", match.index);
}
// regex.lastIndex จะอัปเดตอัตโนมัติ

3. ใช้ replace() กับ Callback Function

const str = "cat bat rat";
const result = str.replace(/(\w+)at/g, (match, group1) => {
    return `[${group1.toUpperCase()}AT]`;
});
// ผลลัพธ์: "[CAT] [BAT] [RAT]"

สรุปเมธอดที่เกี่ยวข้อง

เมธอดคืนค่ารองรับ Flag g
match()Array ของค่าที่ตรง (หรือ null)✅ ใช่
matchAll()Iterator (ต้อง spread [...]) ✅ ใช่
exec()Array รายการเดียว (หรือ null)✅ ใช่ (อัปเดต lastIndex)
test()Boolean (true/false)✅ ใช่ (อัปเดต lastIndex)
search()Index แรกที่พบ (หรือ -1)❌ ไม่ (หาแค่ตัวแรก)