Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách viết RegExp JavaScript cho nhiều khớp (multiple matches)

Để tìm nhiều khớp, viết RegExp với flag g (global) và dùng vòng lặp exec().

Ví dụ: Lấy nhiều tham số 'demo' từ URL

<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, demo = [];
      while (matches = demoRegex.exec(a.search)) {
        demo.push(decodeURIComponent(matches[1]));
      }
      document.write(demo);
    </script>
  </head>
  </body>
</html>