How to Use match Method in JavaScript: Syntax and Examples
The
match() method in JavaScript is used on strings to find matches based on a regular expression. It returns an array of matches or null if no match is found. You use it by calling string.match(regex) where regex is a regular expression pattern.Syntax
The match() method is called on a string and takes one argument: a regular expression (RegExp object). It returns an array of matches or null if no matches are found.
- string: The text you want to search.
- regex: The pattern to find, written as a regular expression.
- Return value: An array of matches or
null.
javascript
string.match(regex)
Example
This example shows how to find all words starting with 'a' in a sentence using match() with a global regular expression.
javascript
const text = "Apples and apricots are amazing."; const matches = text.match(/a\w*/gi); console.log(matches);
Output
["Apples", "and", "apricots", "are", "amazing"]
Common Pitfalls
One common mistake is forgetting the global flag g in the regular expression, which causes match() to return only the first match instead of all matches. Another is using match() on a string without a regular expression, which may not work as expected.
javascript
const text = "Hello hello hello"; // Wrong: missing global flag const firstMatch = text.match(/hello/i); console.log(firstMatch); // Outputs only first match // Right: with global flag const allMatches = text.match(/hello/gi); console.log(allMatches); // Outputs all matches
Output
["Hello"]
["Hello", "hello", "hello"]
Quick Reference
| Feature | Description |
|---|---|
| Input | A string to search |
| Argument | A regular expression (e.g., /pattern/g) |
| Return | Array of matches or null if none |
| Global flag (g) | Returns all matches, not just first |
| Case-insensitive flag (i) | Matches ignoring case |
Key Takeaways
Use
match() on strings with a regular expression to find matches.Include the global flag
g to get all matches, not just the first.If no matches are found,
match() returns null.Regular expressions control what
match() looks for in the string.Without a regular expression,
match() may not behave as expected.