Looping over matches with JavaScript regular expressions

In JavaScript, you can loop over regular expression matches using several methods. The most common approaches are using match() with the global flag, matchAll(), or exec() in a loop.

Using match() with Global Flag

The match() method with the global flag (g) returns an array of all matches, which you can then iterate over:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Regex Matches Loop</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            margin: 20px;
        }
        .sample {
            background-color: #f0f0f0;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        .result {
            color: #007acc;
            font-weight: bold;
            margin: 10px 0;
        }
        button {
            background-color: #007acc;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>Looping over Regex Matches</h2>
    
    <div class="sample">
        There is a cat lying besides the cricket bat and chasing the rat
    </div>
    
    <button onclick="findMatches()">Find Words Ending with "at"</button>
    
    <div class="result" id="result"></div>

    <script>
        function findMatches() {
            const text = "There is a cat lying besides the cricket bat and chasing the rat";
            const regex = /\b\w*at\b/g; // Words ending with 'at'
            const matches = text.match(regex);
            const resultDiv = document.getElementById('result');
            
            resultDiv.innerHTML = '<h3>Matches found:</h3>';
            
            if (matches) {
                matches.forEach((match, index) => {
                    resultDiv.innerHTML += `Match ${index + 1}: "${match}"<br>`;
                });
                resultDiv.innerHTML += `<p>Total matches: ${matches.length}</p>`;
            } else {
                resultDiv.innerHTML += '<p>No matches found.</p>';
            }
        }
    </script>
</body>
</html>

Using matchAll() Method

The matchAll() method returns an iterator of all match objects, providing more detailed information about each match:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MatchAll Example</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .result { background-color: #f9f9f9; padding: 15px; margin: 10px 0; }
        button { padding: 10px 15px; background-color: #28a745; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <h2>Using matchAll() for Detailed Matches</h2>
    
    <button onclick="useMatchAll()">Find Email Addresses</button>
    
    <div class="result" id="matchAllResult"></div>

    <script>
        function useMatchAll() {
            const text = "Contact us at info@example.com or support@test.org for help.";
            const emailRegex = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g;
            const matches = text.matchAll(emailRegex);
            const resultDiv = document.getElementById('matchAllResult');
            
            resultDiv.innerHTML = '<h3>Email addresses found:</h3>';
            
            let count = 0;
            for (const match of matches) {
                count++;
                resultDiv.innerHTML += `Email ${count}: "${match[0]}" (found at position ${match.index})<br>`;
            }
            
            if (count === 0) {
                resultDiv.innerHTML += '<p>No email addresses found.</p>';
            }
        }
    </script>
</body>
</html>

Using exec() in a Loop

For more control over the matching process, you can use exec() in a while loop:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exec Loop Example</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .result { background-color: #e7f3ff; padding: 15px; margin: 10px 0; border-left: 4px solid #2196F3; }
        button { padding: 10px 15px; background-color: #ff6b35; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <h2>Using exec() in a Loop</h2>
    
    <button onclick="useExecLoop()">Find Numbers</button>
    
    <div class="result" id="execResult"></div>

    <script>
        function useExecLoop() {
            const text = "The prices are $25.99, $134.50, and $7.25 respectively.";
            const priceRegex = /\$(\d+\.\d{2})/g;
            const resultDiv = document.getElementById('execResult');
            
            resultDiv.innerHTML = '<h3>Prices found using exec():</h3>';
            
            let match;
            let count = 0;
            
            while ((match = priceRegex.exec(text)) !== null) {
                count++;
                resultDiv.innerHTML += `Price ${count}: ${match[0]} (amount: $${match[1]}) at position ${match.index}<br>`;
            }
            
            if (count === 0) {
                resultDiv.innerHTML += '<p>No prices found.</p>';
            }
        }
    </script>
</body>
</html>

Comparison of Methods

Method Returns Best For Browser Support
match() Array of matches Simple match extraction All browsers
matchAll() Iterator of match objects Detailed match information ES2020+
exec() loop Individual match objects Custom processing logic All browsers

Key Points

  • Always use the global flag (g) when you want to find all matches
  • match() is simplest for basic iteration over matches
  • matchAll() provides more details but requires modern browsers
  • exec() gives you the most control but requires a while loop
  • Remember to handle cases where no matches are found

Conclusion

JavaScript offers multiple ways to loop over regex matches. Use match() for simple cases, matchAll() for detailed information, or exec() for custom processing logic. Choose the method that best fits your specific use case and browser requirements.

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

953 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements