How to Use the String match() Method in JavaScript

Contents
In this article, you will learn how to use the string match() method in JavaScript.
Using the string match() method in JavaScript
The match() method is a powerful built-in function in JavaScript that allows you to search a string for a specified pattern and returns the matches as an array.
Syntax
The syntax for using the match() method is as follows:
string.match(regexp)
Here, “string” is the string that you want to search, and “regexp” is the regular expression pattern you want to match. The match() method returns an array of matches if any, otherwise, it returns null.
Examples
Using the match() method to match a string pattern
const str = "I have 5 dogs and 2 cats";
const regex = /\d+/g;
const matches = str.match(regex);
console.log(matches); // ["5", "2"]
In this example, we have used the match() method to match a regular expression pattern that matches one or more digits. The “g” flag is used to search for multiple occurrences of the pattern in the string. The match() method returns an array containing the two matched digits.
Using the match() method with capturing groups
const str = "John Doe (30 years)";
const regex = /(\w+)\s(\w+)\s\((\d+)\s\w+\)/;
const matches = str.match(regex);
console.log(matches); // ["John Doe (30 years)", "John", "Doe", "30"]
In this example, we have used the match() method to match a regular expression pattern that matches a name, followed by an age in parentheses. The pattern uses capturing groups to extract the matched name and age. The match() method returns an array containing the entire matched string, followed by the captured groups.
Using the match() method with a global flag
const str = "The quick brown fox jumps over the lazy dog";
const regex = /the/gi;
const matches = str.match(regex);
console.log(matches); // ["the", "the"]
In this example, we have used the match() method to match a regular expression pattern that matches the word “the” (case-insensitive) in the string. The “g” flag is used to search for multiple occurrences of the pattern in the string. The match() method returns an array containing both occurrences of the matched word.