String.prototype.match
Finds matches of a regular expression.
Available since: ES3
Syntax
str.match(regexp)Parameters
| Parameter | Type | Description |
|---|---|---|
| regexp | RegExp | A regular expression. |
Return value
Array | nullWithout g — the match with groups; with g — an array of all matches; null if nothing is found.
Examples
With the g flag — all matches:
console.log('Call 555-1234 or 555-9876'.match(/\d{3}-\d{4}/g));Output:
[
"555-1234",
"555-9876"
]Without g — the first match and its groups:
const match = 'Price: 42 USD'.match(/(\d+) (\w+)/);
console.log(match[1], match[2]);Output:
42 USDNothing found:
const found = 'hello'.match(/\d+/g);
console.log(found);
console.log(found ?? []);Output:
null
[]Notes
If there are no matches the result is null, not an empty array, so 'hello'.match(/\d/g).length throws an error. Provide a default: str.match(re) ?? [].
See also
- String.prototype.matchAll — Returns every match together with its groups.
- RegExp.prototype.test — Checks whether a string matches a pattern.
- RegExp.prototype.exec — Finds a match and returns the details: groups and position.
Related recipes
In the tutorial
- Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.