How to find all match strings using RegEx in JavaScript?
How to find all match strings using RegEx in JavaScript?
20531-Oct-2023
Updated on 02-Nov-2023
Home / DeveloperSection / Forums / How to find all match strings using RegEx in JavaScript?
How to find all match strings using RegEx in JavaScript?
Aryan Kumar
02-Nov-2023To 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:
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:
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.