Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return Value
5.
Example 1: Using the /g Flag (Global)
6.
Example 2: Using the /i Flag (Case-Insensitive)
7.
Example 3: Using the /gi Flag (Global and Case-Insensitive)
8.
The Difference Between String match() and String search()
9.
Regular Expression Search Methods  
9.1.
1. What is a Regular Expression?  
9.2.
2. Using Regular Expressions with `match()`  
9.3.
3. Using Regular Expressions with `search()`  
9.4.
4. Common Regex Patterns  
9.5.
5. Flags in Regular Expressions  
10.
Supported Browsers
11.
Frequently Asked Questions
11.1.
What happens if there are no matches?
11.2.
What is the difference between match() and matchAll()?
11.3.
Can I use match() without any flags?
12.
Conclusion
Last Updated: Jan 21, 2025
Easy

What is match() Method in JavaScript?

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The JavaScript match() Method is a built-in function used to search for a match between a string and a regular expression. It is often used when you need to extract specific patterns from a string, such as finding all occurrences of a word, validating formats like email addresses, or retrieving numbers from text. The method returns an array of matches or null if no match is found.

In this article, we will discuss the match() method, its syntax, parameters, return values, and various examples demonstrating its usage.

Syntax

The syntax of the match() method is as follows:

string.match(regexp)

Parameters

  • regexp: This is a regular expression that defines the pattern you want to match. It can include flags like g (global), i (case-insensitive), and m (multiline).

Return Value

The match() method returns:

  • If the g flag is used: An array of all matches.
     
  • If the g flag is not used: An array with details about the first match or null if no match is found.
     
  • If no match is found: Returns null.

Example 1: Using the /g Flag (Global)

The /g flag ensures that all matches of the pattern are found.

Example:

const text = "The quick brown fox jumps over the lazy dog.";
const result = text.match(/o/g);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

[ "o", "o", "o" ]


Explanation:

  • The regular expression /o/g searches for the letter "o" in the string.
  • The g flag finds all occurrences of "o" and returns them in an array.

Example 2: Using the /i Flag (Case-Insensitive)

The /i flag makes the pattern matching case-insensitive.

Example:

const text = "The quick brown fox jumps over the Lazy Dog.";
const result = text.match(/lazy/i);


console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

[ "Lazy" ]


Explanation:

  • The regular expression /lazy/i matches the word "lazy" regardless of its case.
     
  • The output contains the first match, which is "Lazy."

Example 3: Using the /gi Flag (Global and Case-Insensitive)

The /gi flag combines global search with case-insensitive matching.

Example:

const text = "JavaScript is a versatile language. JAVASCRIPT is widely used.";
const result = text.match(/javascript/gi);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output:

[ "JavaScript", "JAVASCRIPT" ]


Explanation:

  • The regular expression /javascript/gi matches all occurrences of "JavaScript," ignoring case.
     
  • The result is an array of all matches.

The Difference Between String match() and String search()

Featurematch()search()
Return ValueReturns an array containing the matched results, or null if no match is found.Returns the index of the first match found, or -1 if no match is found.
Global SearchAllows the use of regular expressions with the g flag to perform a global search and return all matches.Always performs a single search, returning only the index of the first match.
Capture GroupsProvides access to capture groups and other regular expression features when a regular expression is used.Does not provide access to capture groups or other advanced regular expression features.
Use CaseIdeal for extracting specific parts of a string based on a pattern.Best suited for simple substring searches where only the position of the first match is needed.

Regular Expression Search Methods  

Regular expressions (regex) are powerful tools for pattern matching in JavaScript. They allow you to define complex search patterns & are often used with methods like `match()` & `search()`. Let’s understand how regular expressions work & how they can be used effectively in JavaScript.  

1. What is a Regular Expression?  

A regular expression is a sequence of characters that defines a search pattern. It can be letters, numbers, special characters, & modifiers. In JavaScript, regex is created using slashes (`/`).  

For example:  

const pattern = /hello/;


This regex pattern matches the word "hello" in a string.  

2. Using Regular Expressions with `match()`  

The `match()` method works seamlessly with regex to find patterns in strings. Let’s look at a proper example:  

const text = "The quick brown fox jumps over the lazy dog.";
const pattern = /[A-Za-z]+/g; // Matches all words
const result = text.match(pattern);
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[
  "The", "quick", "brown", 
  "fox", "jumps", "over", 
  "the", "lazy", "dog"
]


In this example:  

  • The regex `/[A-Za-z]+/g` matches all sequences of letters (words) in the string.  
     
  • The `match()` method returns an array of all matched words.  

3. Using Regular Expressions with `search()`  

The `search()` method can also use regex to find the position of a pattern in a string. For example:  

const text = "The quick brown fox jumps over the lazy dog.";
const pattern = /fox/; // Matches the word "fox"
const result = text.search(pattern);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

16


In this example:  

  • The regex `/fox/` matches the word "fox".  
     
  • The `search()` method returns the starting index of the match, which is `16`.  

4. Common Regex Patterns  

Let’s take a look at some commonly used regex patterns:  

  • Digits: `/\d/` matches any digit (0-9).  
     
  • Word Characters: `/\w/` matches any letter, digit, or underscore.  
     
  • Whitespace: `/\s/` matches any whitespace character (space, tab, newline).  
     
  • Quantifiers:  

- `+` matches one or more occurrences.  

- `` matches zero or more occurrences.  

- `?` matches zero or one occurrence.  

Example:  

const text = "Email: user@example.com, Phone: 123-456-7890";
const emailPattern = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
const phonePattern = /\d{3}-\d{3}-\d{4}/g;
const emails = text.match(emailPattern);
const phones = text.match(phonePattern);
console.log(emails); 
console.log(phones); 
You can also try this code with Online Javascript Compiler
Run Code


Output:

["user@example.com"]
 ["123-456-7890"]


In this example:  

  • The regex `/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g` matches email addresses.  
     
  • The regex `/\d{3}-\d{3}-\d{4}/g` matches phone numbers in the format `123-456-7890`.  

5. Flags in Regular Expressions  

Flags modify how the regex works. Common flags include:  

  • `g`: Global search (find all matches).
      
  • `i`: Case-insensitive search.  
     
  • `m`: Multiline search.  


Example:  

const text = "Hello hello HELLO";
const pattern = /hello/gi; // Case-insensitive & global search
const result = text.match(pattern);
console.log(result); 
You can also try this code with Online Javascript Compiler
Run Code


Output: 

["Hello", "hello", "HELLO"]


In this example:  

  • The `i` flag makes the search case-insensitive.  
     
  • The `g` flag ensures all matches are returned.  

Supported Browsers

The match() method is supported in all major browsers, making it highly reliable for web development. Below is a compatibility table:

BrowserSupported Version
Google ChromeAll versions
Mozilla FirefoxAll versions
Microsoft EdgeAll versions
SafariAll versions
OperaAll versions

Frequently Asked Questions

What happens if there are no matches?

If no match is found, the match() method returns null.

What is the difference between match() and matchAll()?

The match() method returns an array or null, while matchAll() returns an iterator that provides all matches along with detailed information.

Can I use match() without any flags?

Yes, you can use match() without flags. In this case, it returns only the first match.

Conclusion

The JavaScript match() method is a powerful tool for working with strings and patterns. It allows you to find specific sequences in a string using regular expressions, making it essential for tasks like validation and data extraction. By mastering its syntax and flags, we can efficiently handle string operations in your projects.

Live masterclass