JavaScript Reference ยท String
String.prototype.match()
Reference for JavaScript String.prototype.match(): find regular expression matches, read capture groups, use the g flag and handle the null result.
The match() method runs a regular expression against a string and returns the result. Its answer has two different shapes depending on the g (global) flag, which is the main thing to remember.
Without g, you get the first match in detail, including capture groups and its position. With g, you get a plain array of every matched text and nothing else. If nothing matches, the result is null in both cases.
"order 66".match(/\d+/); // an array whose first item is "66"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
string.match(regexp)
| Name | Description |
|---|---|
regexp |
A regular expression object. Anything else is passed to new RegExp(value), so a string is treated as a pattern, not as literal text. |
Return value:
- Without the
gflag: an array like the oneexec()returns. Item0is the whole match, items1and up are the capture groups, and the array has the propertiesindex(where the match starts),input(the original string) andgroups(an object of named groups, orundefined). - With the
gflag: an array of all matched strings, with no groups and no positions. - If there is no match:
null.
Exceptions: a SyntaxError if a non-regex argument is not a valid pattern, such as "(".
Usage notes
- Check for
nullfirst.text.match(/x/)[0]throws if there is no match. Use?., or?? []as in the second example. gdrops the groups. To get groups and indexes for every match, usematchAll()or loop withexec().- Strings become patterns.
"a.b".match(".")matches any character, so the first match is"a". Escape special characters, or useincludes()for plain text. - Only testing? If you just need true or false,
RegExp.prototype.test()is clearer and avoids building the array. - Only the position?
search()returns the index of the first match. - A sticky
yflag withoutgmatches only atlastIndex. Most code never needs this. - Calling without an argument matches the empty pattern and returns an array with an empty string.
- Empty matches such as
/a*/gcan appear between characters. The engine advances by one position so loops do not hang. match()does not change the string, and for non-global regexes it leaveslastIndexalone; for global ones it resets it to0.
Browser support
match() works in every browser. Named groups and the d flag (match indices) are newer, so check a compatibility table if you must support old browsers.