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

วิธีเขียน Regular Expression สำหรับ Multiple Matches ใน JavaScript

ใช้ Regular Expression พร้อม Flag g (Global) และเมธอด exec() ในลูป เพื่อหา Multiple Matches ทั้งหมดในสตริง

ตัวอย่าง: ดึงค่า query parameter ซ้ำ (demo=...)

<html>
  <head>
    <script>
      var url = 'https://www.example.com/new.html?ui=7&demo=one&demo=two&demo=three four';
      var a = document.createElement('a');
      a.href = url;

      var demoRegex = /(?:^|[&;])demo=([^&;]+)/g;
      var matches;
      var demo = [];

      while (matches = demoRegex.exec(a.search)) {
        demo.push(decodeURIComponent(matches[1]));
      }

      document.write(demo); // one,two,three four
    </script>
  </head>
  </body>
</html>

อธิบาย Regex: /(?:^|[&;])demo=([^&;]+)/g

ส่วนความหมาย
(?:^|[&;])Non-capturing group: เริ่มสตริง (^) หรือ & หรือ ;
demo=Literal "demo="
([^&;]+)Capture Group 1: ตัวอักษรที่ไม่ใช่ & หรือ ; หนึ่งขึ้นไป
gGlobal flag - หาทุกครั้ง

วิธีทันสมัย (ES6+)

// 1. URLSearchParams (แนะนำสำหรับ URL)
const url = 'https://example.com?demo=one&demo=two&demo=three';
const params = new URLSearchParams(new URL(url).search);
const demoValues = params.getAll('demo'); // ["one", "two", "three"]

// 2. String.matchAll() (ES2020) - คืน Iterator
const regex = /(?:^|[&;])demo=([^&;]+)/g;
const matches = [...url.matchAll(regex)].map(m => decodeURIComponent(m[1]));
// ["one", "two", "three"]

// 3. String.match() กับ g flag (คืนแค่ full matches)
// ต้องใช้ exec ในลูป หรือ matchAll แทน

แนะนำ: ใช้ URLSearchParams สำหรับ Query String ใช้ matchAll สำหรับ Regex ทั่วไป