String.prototype.match()
The match()
method retrieves the result of matching a string against a regular expression.
Syntax
match(regexp)
Parameters
regexp
: A regular expression object, or any object that has a
Symbol.match
method.If
regexp
is not aRegExp
object and does not have aSymbol.match
method, it is implicitly converted to aRegExp
by usingnew RegExp(regexp)
.If you don't give any parameter and use the
match()
method directly, you will get anArray
with an empty string:[""]
, because this is equivalent tomatch(/(?:)/)
.
Return value
An Array
whose contents depend on the presence or absence of the global (g
) flag, or null
if no matches are found.
- If the
g
flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. - If the
g
flag is not used, only the first complete match and its related capturing groups are returned. In this case,match()
will return the same result asRegExp.prototype.exec()
(an array with some extra properties).
Description
The implementation of String.prototype.match
itself is very simple — it simply calls the Symbol.match
method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[@@match]()
.
- If you need to know if a string matches a regular expression
RegExp
, useRegExp.prototype.test()
. - If you only want the first match found, you might want to use
RegExp.prototype.exec()
instead. - If you want to obtain capture groups and the global flag is set, you need to use
RegExp.prototype.exec()
orString.prototype.matchAll()
instead.
For more information about the semantics of match()
when a regex is passed, see RegExp.prototype[@@match]()
.