Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
"order 66".match(/\d+/); // an array whose first item is "66"

Try it

JS Without the g flag: details of one match

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS With g, and when nothing matches

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 g flag: an array like the one exec() returns. Item 0 is the whole match, items 1 and up are the capture groups, and the array has the properties index (where the match starts), input (the original string) and groups (an object of named groups, or undefined).
  • With the g flag: 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 null first. text.match(/x/)[0] throws if there is no match. Use ?., or ?? [] as in the second example.
  • g drops the groups. To get groups and indexes for every match, use matchAll() or loop with exec().
  • Strings become patterns. "a.b".match(".") matches any character, so the first match is "a". Escape special characters, or use includes() 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 y flag without g matches only at lastIndex. 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*/g can 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 leaves lastIndex alone; for global ones it resets it to 0.

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.