Supported Browser
JavaScript String match() Method
The match() method checks if a string fits a pattern defined by a regular expression. It gives back an array with the matches it finds. If there’s no match, it returns null. YOu can often use this method to find specific patterns within strings.
Syntax
string.match(regExp);
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.
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.
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.
// 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.
// 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.
// 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.