JavaScript match() Method
Example
Find "ain" in a string:
var
str
=
"
The rain in SPAIN stays mainly in the plain
"
;
var
n
=
str
.
match
(
/
ain
/
g
)
;
n Output the array result values:
Try it »
Definition and Usage
The match() method can search for a specified value within a string, or find one or more matches for a regular expression.
If you want to learn more about regular expressions, please see our: RegExp Tutorial and our RegExp Object Reference Manual.
Note: The match() method searches the string String Object to find one or more texts matching regexp. The behavior of this method largely depends on whether regexp has the flag g. If regexp does not have the flag g, the match() method can only perform one match in stringObject. If no matching text is found, match() returns null. Otherwise, it returns an array containing information about the matched text it found.
Browser support





All major browsers support the match() method.
Syntax
string
.match(
regexp
)
Parameter value
| Parameters | Description |
|---|---|
| regexp | Required. A RegExp object specifying the pattern to match. If this argument is not a RegExp object, it must first be passed to the RegExp constructor to convert it into a RegExp object. |
Return Value
| Type | Description |
|---|---|
| Array | An array holding the match results. The contents of the array depend on whether regexp has the global flag g. If no match is found, it returns null . |
Technical Details
| JavaScript version: | 1.2 |
|---|
More examples
Example
Globally search for the string "ain" without case sensitivity:
var
str
=
"
The rain in SPAIN stays mainly in the plain
"
;
var
n
=
str
.
match
(
/
ain
/
gi
)
;
n Output result:
ain,AIN,ain,ain
Try it »
Example
Determine whether it is the WeChat browser:
function
is_weixn
(
)
{
var
ua
=
navigator
.
userAgent
.
toLowerCase
(
)
;
if
(
ua
.
match
(
/
MicroMessenger
/
i
)
==
"
micromessenger
"
)
{
return
true
;
}
else
{
return
false
;
}
}
Try it »
JavaScript String object