JavaScript String match() Method
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
function matchString() {
let string = "Welcome to geeks for geeks" ;
let result = string.match(/eek/g);
console.log( "Output : " + result);
} matchString();
|
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
function matchString() {
let string = "Welcome to GEEKS for geeks!" ;
let result = string.match(/eek/i);
console.log( "Output : " + result);
} matchString();
|
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
function matchString() {
let string = "Welcome to GEEKS for geeks!" ;
let result = string.match(/eek/gi);
console.log( "Output : " + result);
} matchString();
|
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
Share your thoughts in the comments
Please Login to comment...