Javascript - String match() Method

The match() method matches a string against a regular expression, and returns the matches, as an Array object.

Description

The match() method matches a string against a regular expression, and returns the matches, as an Array object.

If the regular expression does not include the g modifier to perform a global search, the match() method will return only the first match.

It returns null if no match is found.

Syntax

string.match(regexp)

Parameter Values

Parameter Require Description
regexpRequired. The value to search for, as a regular expression.

Return

An Array, containing the matches, one item for each match, or null if no match is found

Example

Search a string for "ain":

Demo

//perfom a global search for the letters "ain" in a string, and display the matches.
var str = "test this is a test rain Main MAIN";
var res = str.match(/ain/g);
console.log(res);//from   w  w w .  ja va2 s .  com

//Perform a global, case-insensitive search for "ain":
var str = "test this is a test rain Main MAIN";
var res = str.match(/ain/gi);
console.log(res);

Result