How to write JavaScript Regular Expression for multiple matches?

To find multiple matches in JavaScript, use the global flag (g) with regular expressions. The exec() method can be called repeatedly to find all matches in a string.

Syntax

let regex = /pattern/g;
let matches;
while ((matches = regex.exec(string)) !== null) {
    // Process each match
}

Example: Extracting URL Parameters

This example extracts all demo parameters from a URL query string:

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

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

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

document.write("Found parameters: " + demo.join(", "));
</script>
</head>
<body>
</body>
</html>

Output

Found parameters: one, two, three

How It Works

The regular expression /(?:^|[&;])demo=([^&;]+)/g breaks down as:

  • (?:^|[&;]) - Non-capturing group matching start of string or &/; characters
  • demo= - Literal text "demo="
  • ([^&;]+) - Capturing group for parameter value (everything except & or ;)
  • g - Global flag for multiple matches

Modern Alternative Using matchAll()

ES2020 introduced matchAll() for cleaner multiple matching:

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

var demoRegex = /(?:^|[&;])demo=([^&;]+)/g;
var matches = Array.from(a.search.matchAll(demoRegex));
var demo = matches.map(match => decodeURIComponent(match[1]));

document.write("Using matchAll: " + demo.join(", "));
</script>
</head>
<body>
</body>
</html>

Key Points

  • Always use the global flag (g) for multiple matches
  • The exec() method returns null when no more matches are found
  • Each match includes the full match and captured groups
  • matchAll() provides a more modern, cleaner approach

Conclusion

Use the global flag with exec() in a while loop for multiple regex matches. Modern browsers support matchAll() as a cleaner alternative.

Updated on: 2026-03-15T23:18:59+05:30

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements