---
title: "How to find all match strings using RegEx in JavaScript?"  
description: "How to find all match strings using RegEx in JavaScript?"  
author: "Utpal Vishwas"  
published: 2023-10-31  
updated: 2023-11-02  
canonical: https://www.mindstick.com/forum/160354/how-to-find-all-match-strings-using-regex-in-javascript  
category: "javascript"  
tags: ["javascript object", "javascript regex"]  
reading_time: 2 minutes  

---

# How to find all match strings using RegEx in JavaScript?

How to find all [match](https://www.mindstick.com/forum/159713/regex-match-attribute-in-an-html-code) [strings](https://www.mindstick.com/forum/161912/explain-the-python-strings) using [RegEx](https://www.mindstick.com/forum/160352/how-to-use-regex-in-javascript-for-pattern-matching) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

To find all matching strings using regular expressions (regex) in JavaScript, you can use the **.match()** method with the global (**g**) flag or use the **.exec()** method in a loop. Here are both approaches:

## Using .match() with the global (g) flag:

The **.match()** method with the global flag will return an array of all matching strings found in the input string. Here's how to use it:

```plaintext
const inputString = "Hello, I have 3 cats and 2 dogs, but I want more cats.";

const regex = /\d+ cat/g; // Regular expression to match numbers followed by "cat"

const matches = inputString.match(regex);

console.log(matches); // Output: ["3 cat"]
```

In this example, the regular expression **/d+ cat/g** is used to match numbers followed by "cat" in the input string. The **.match()** method with the global flag (**g**) returns an array of all matching strings.

## Using .exec() in a loop:

You can also use the **.exec()** method in a loop to find all matching strings one by one. Here's an example:

```plaintext
const inputString = "Hello, I have 3 cats and 2 dogs, but I want more cats.";
const regex = /\d+ cat/g; // Regular expression to match numbers followed by "cat"

let match;
const matches = [];

while ((match = regex.exec(inputString)) !== null) {
  matches.push(match[0]);
}

console.log(matches); // Output: ["3 cat"]
```

In this example, we use a **while** loop with the **.exec()** method to iterate through the input string and collect all matching strings in the **matches** array. The loop continues until no more matches are found.

Both approaches will help you find all matching strings in a given input string using regular expressions in JavaScript.


---

Original Source: https://www.mindstick.com/forum/160354/how-to-find-all-match-strings-using-regex-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
