JavaScript .match()
The .match() method searches a string for matches against a regular expression and returns the result as an array object. The .match() method is used in JavaScript to find parts of a string that match a regular expression. It is commonly applied in tasks such as extracting numbers or words, validating formats like email addresses, or parsing structured text.
Syntax
string.match(regex)
Parameters:
regex: A regular expression object to match against the string.
Return value:
- If the regular expression has the
gflag: Returns an array of all matches found, ornullif no match is found. - Without the
gflag: Returns an array with detailed information about the first match (including captured groups), ornullif no match is found.
Example 1: Using .match() to Find Uppercase Letters in a String
In the following example, a string variable paragraph contains a sentence, and regex defines a regular expression to match all uppercase letters. The .match() method applies this regex to the string and returns an array of all matches:
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';const regex = /[A-Z]/g;console.log(paragraph.match(regex));
The output of this code will be:
[ 'T', 'I' ]
If the “g” flag is not used, it returns the array object with the result at index 0:
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';const regex = /[A-Z]/;console.log(paragraph.match(regex));
The output of this code will be:
['T',index: 0,input: 'The quick brown fox jumps over the lazy dog. It barked.',groups: undefined]
Example 2: Finding All Occurrences of a Word Using .match()
This example demonstrates how to use the .match() method to find all occurrences of the word “Hello” in a string:
The output of this code is:
[ 'Hello', 'Hello' ]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours