The JavaScript string.match() method
The match() method searches a string with a regular expression and returns the matches as an array, or null if there are none. With the global flag /g it returns all matched strings; without it, it returns the first match plus capture groups. Check for null before using the result.
Overview
match() runs a regular expression against a string and tells you what it found. Pass it a regex and it returns an array of matches — or null when there's nothing, which is the result you must guard against before indexing into it.
Its behavior depends on the global flag. With /g, match() returns a flat array of all matched substrings: "a1b2c3".match(/\\d/g) gives ["1", "2", "3"]. Without /g, it returns details for just the first match — the full match at index 0, then any capture groups, plus index and input properties — which is what you want when you need the captured pieces.
When you want all matches and their capture groups together, the newer matchAll() is the right tool: it returns an iterator of full match objects you can loop with for...of. For a quick yes/no "does it match", regex.test(str) is simpler than match(), and for find-and-replace use replace().
Syntax
str.match(regexp)
"a1b2c3".match(/\d/g) // ["1", "2", "3"] (global)
"2026-06-23".match(/(\d+)-(\d+)/) // ["2026-06", "2026", "06", ...]
"abc".match(/x/) // null
Parameters
The string.match() method accepts the following parameters.
| Parameter | Description |
|---|---|
regexp |
A regular expression to match against. A non-regex argument is converted to one. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const text = 'Call 555-1234 or 555-5678';
const numbers = text.match(/\d{3}-\d{4}/g);
document.getElementById('out').textContent =
numbers ? numbers.join('\n') : 'no matches';
// 555-1234 / 555-5678
</script>
Best practices
- Always check for
null—match()returns it when there's no match. - Use the
/gflag to get every matched string; omit it to get the first match with capture groups. - Use
matchAll()when you need all matches and their groups together. - For a simple "does it match?" check,
regex.test(str)is clearer.
Frequently asked questions
What does string match() return?
null if there are none. With the /g flag it returns all matched strings; without it, the first match plus capture groups.How do I get all matches of a regex?
str.match(/pattern/g). For matches with capture groups, use str.matchAll(/pattern/g).What is the difference between match() and matchAll()?
match() with /g returns just the matched strings; matchAll() returns an iterator of full match objects (with groups) for every match.How do I just check if a string matches a pattern?
regex.test(str), which returns a boolean — simpler than match() when you only need yes/no.