Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.match

Finds matches of a regular expression.

Available since: ES3

Syntax

str.match(regexp)

Parameters

ParameterTypeDescription
regexpRegExpA 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 USD

Nothing 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

Related recipes

In the tutorial

  • Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.

Thanks for reading!

Donate to the site — we work hard for you.