JavaScript match()
Method
Example
Search for "ain" in the string:
var str = "The rain in SPAIN stays mainly in the plain";
var n = str.match(/ain/g);
n outputs the array result:
Definition and Usage
The match()
method searches a string for a match against a specified value or finds one or more regular expression matches.
For more information on regular expressions, please refer to our RegExp Tutorial and our RegExp Object Reference.
Note: The match()
method searches the string object for one or more matches with the regexp. The behavior of this method largely depends on whether the regexp has the global flag g. If the regexp does not have the g flag, match()
will only perform one match in the string object. If no matches are found, match()
returns null. Otherwise, it returns an array containing information about the matched text.
Browser Support
All major browsers support the match()
method.
Syntax
Parameter Values
Parameter | Description |
---|---|
regexp | Required. The RegExp object specifying the pattern to match. If this parameter is not a RegExp object, it needs to be passed to the RegExp constructor first to convert it into a RegExp object. |
Return Value
Type | Description |
---|---|
Array | An array containing the matching results. The content of this array depends on whether the regexp has the global flag g. If no match is found, it returns null. |
Technical Details
| JavaScript Version: | 1.2 | | --- | --- |
More Examples
Example
Global search for "ain" in the string, case-insensitive:
var str = "The rain in SPAIN stays mainly in the plain";
var n = str.match(/ain/gi);
n output:
ain,AIN,ain,ain
Example
Check if the browser is WeChat:
function is_weixn(){
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
}