Open In App

JavaScript String match() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript String match() method searches a string for a specified pattern using regular expressions. It returns an array of all matches found, or null if no matches are found.

String match() Method Syntax

string.match(regExp);

String match() Method Parameters

  • string: The string to be searched.
  • regexp: A regular expression object or a regular expression pattern string to be searched for within the string.

Note: If the g flag is not used with the regular expression, only the first match will be returned. If the g flag is used, all matches will be returned.

String match() Method Return Value

Returns an array that contains the matches and one item for each match or if the match is not found then it will return Null. 

String match() Method Examples

Example 1: Using /g flag

Here, the substring “eek” will match with the given string, and when a match is found, it will return an array of string objects. Here “g” flag indicates that the regular expression should be tested against all possible matches in a string. 

javascript




// Initializing function to demonstrate match()
// method with "g" para
function matchString() {
    let string = "Welcome to geeks for geeks";
    let result = string.match(/eek/g);
    console.log("Output : " + result);
} matchString();


Output

Output : eek,eek



Example 2: Using /i flag 

Here, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “i” parameter helps to find the case-insensitive match in the given string. 

javascript




// Initializing function to demonstrate match()
// method with "i" para
function matchString() {
    let string = "Welcome to GEEKS for geeks!";
    let result = string.match(/eek/i);
    console.log("Output : " + result);
} matchString();


Output

Output : EEK



Example 3: Using /gi flag

Here, the substring “eek” will match with the given string, and it will return instantly if it found the match. Here “gi” parameter helps to find the case-insensitive match AND all possible combinations in the given string. 

javascript




// Initializing function to demonstrate match()
// method with "gi" para
function matchString() {
    let string = "Welcome to GEEKS for geeks!";
    let result = string.match(/eek/gi);
    console.log("Output : " + result);
} matchString();


Output

Output : EEK,eek



We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browser



Last Updated : 05 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads