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

สกัดข้อความในเครื่องหมายคำพูดด้วย Regex ใน JavaScript


ใช้ Regular Expression /"(.*?)"/g เพื่อจับข้อความภายในเครื่องหมายคำพูดคู่ ("...") แบบ Non-greedy (จับน้อยที่สุด) Flag g (Global) ใช้หาทุกคู่ที่มีในสตริง

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Extract Quoted Text</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: red; }
  </style>
</head>
<body>
  <h1>สกัดข้อความในเครื่องหมายคำพูดด้วย Regex</h1>
  <div style="color: green;" class="result">Hello "World" and "JavaScript"</div>
  <div class="sample"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อดึงข้อความระหว่างเครื่องหมายคำพูด</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btnEle = document.querySelector(".Btn");
    const sampleEle = document.querySelector(".sample");
    // Non-greedy: จับน้อยที่สุดจนเจอ "
    const regex = /"([^"]*)"/g; // แนะนำ: ใช้ [^"]* แทน .*? (เร็วกว่า ปลอดภัยกว่า)
    btnEle.addEventListener("click", () => {
      const text = resEle.textContent;
      const matches = text.match(regex);
      if (matches) {
        sampleEle.textContent = "พบ: " + matches.join(", ");
      } else {
        sampleEle.textContent = "ไม่พบข้อความในเครื่องหมายคำพูด";
      }
    });
  </script>
</body>
</html>

ผลลัพธ์

สกัดข้อความในเครื่องหมายคำพูดด้วย Regex ใน JavaScript

เมื่อกดปุ่ม "คลิกที่นี่":

สกัดข้อความในเครื่องหมายคำพูดด้วย Regex ใน JavaScript

Regex Pattern แบบละเอียด

/"([^"]*)"/g
// "      จับเครื่องหมายคำพูดเปิด
// (      เริ่ม Capture Group
// [^"]*  ตัวอักษรใดๆ ยกเว้น " (0 ตัวขึ้นไป) - Negated Character Class
// )      จบ Capture Group
// "      จับเครื่องหมายคำพูดปิด
// g      Global - หาทุกคู่ในสตริง

ทำไมใช้ [^"]* แทน .*??

  • Performance: [^"]* เร็วกว่า (ไม่ต้อง backtrack)
  • Correctness: .*? Non-greedy แต่อาจจับข้ามบรรทัด/คำพูดซ้อนได้หากไม่ระวัง
  • Readability: ชัดเจนว่า "จับจนกว่าจะเจอคำพูดปิด"

ตัวอย่างเพิ่มเติม

const text = 'He said "Hello" and she replied "Hi there"';

// 1. match() - คืน Array ของ Full Match (รวมเครื่องหมายคำพูด)
text.match(/"([^"]*)"/g); // ['"Hello"', '"Hi there"']

// 2. matchAll() - คืน Iterator ของ Match Objects (มี Groups) - ES2020
[...text.matchAll(/"([^"]*)"/g)].map(m => m[1]); // ['Hello', 'Hi there']

// 3. exec() ใน Loop (เก่า)
const regex = /"([^"]*)"/g;
let match;
while ((match = regex.exec(text)) !== null) {
  console.log(match[1]); // Group 1 = ข้อความภายใน
}

// 4. replace() - แทนที่
text.replace(/"([^"]*)"/g, "'$1'"); // 'Hello' and 'Hi there'

// 5. รองรับ Escape Quote (\" )
const regexEscaped = /"((?:[^"\\]|\\.)*)"/g;
// (?:[^"\\]|\\.)* = ไม่ใช่ " หรือ \ หรือ Escape Sequence (\", \\, \n ฯลฯ)

กรณีขอบเขต (Edge Cases)

InputResult with /"([^"]*)"/gหมายเหตุ
Hello "World"["World"]ปกติ
Hello "World" and "JS"["World", "JS"]หลายคู่
Hello "Wor"ld"["Wor"]หยุดที่ " แรก
Hello "Escaped \" Quote"["Escaped \"]ต้องใช้ Pattern รองรับ Escape
Single 'Quote'[]ไม่จับ Single Quote

Single Quotes

// จับ Single Quote
/"([^']*)"/g // ผิด - ผสม " และ '
/'([^']*)'/g // ถูกสำหรับ Single Quote
// หรือรวมทั้งคู่
/(['"])([^'"]*)\1/g // \1 = Backreference ต้องตรงกับ Quote เปิด