ArticleZip > Javascript How To Get Multiple Matches In Regex Exec Results

Javascript How To Get Multiple Matches In Regex Exec Results

When working with regular expressions in JavaScript, the `exec()` method is a handy tool for extracting information from strings based on a defined pattern. It returns an array containing the matched groups. However, what if you want to get multiple matches from the same string? In this article, we'll explore how to achieve this with ease.

To get multiple matches in the `exec()` results, you can simply loop through the string until there are no more matches left. Here's a step-by-step guide on how to do it:

### Understanding the `exec()` Method
The `exec()` method is a RegExp object method that searches a string for a specified pattern and returns the matched text. It also updates the properties of the RegExp object for the next search.

### Looping Through Multiple Matches
To get multiple matches using the `exec()` method, you can create a loop that continues to execute the method until it returns `null`, indicating that no more matches are found. Here's an example demonstrating this:

Javascript

const regex = /your-regex-pattern/g; // Ensure to use the 'g' flag for global search
let match;

while ((match = regex.exec(yourString)) !== null) {
    // Access the matched values using match[index]
}

In this code snippet:
- Replace `/your-regex-pattern/g` with your actual regular expression pattern. The `g` flag is crucial for global searching.
- Iterate through the string `yourString` using the `exec()` method until no more matches are found.
- Access the matched values using the `match` object inside the loop.

### Practical Example
Let's say you have a string containing multiple occurrences of a word surrounded by hashtags. You want to extract all these words using regular expressions. Here's how you can achieve this:

Javascript

const text = "#apple# is a fruit, #banana# is also a fruit.";
const regex = /#(w+)#/g;
let match;

while ((match = regex.exec(text)) !== null) {
    console.log(match[1]); // Output: apple, banana
}

In this example, the regular expression `/#(w+)#/g` matches words enclosed in hashtags. The loop iterates through the string `text`, extracting and logging all matched words.

### Conclusion
By utilizing a simple loop and the `exec()` method with appropriate regular expressions, you can efficiently obtain multiple matches in JavaScript. This technique is valuable for scenarios where you need to process several occurrences of a pattern within a string.

Experiment with different regular expressions and scenarios to enhance your understanding and proficiency. Remember, practice makes perfect!

×