How to Use match() Method in JavaScript Strings
In JavaScript, use the
match() method on a string to find matches based on a regular expression. It returns an array of matches or null if no match is found.Syntax
The match() method is called on a string and takes a regular expression as its argument. It returns an array of matches or null if no matches are found.
string.match(regexp): The string to search.regexp: A regular expression to match against the string.
javascript
const result = string.match(regexp);Example
This example shows how to find all words starting with 'b' in a sentence using match() with a global regular expression.
javascript
const sentence = "The big brown bear bought blueberries."; const matches = sentence.match(/b\w+/g); console.log(matches);
Output
["big", "brown", "bear", "bought", "blueberries"]
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.
Also, if no match is found, match() returns null, so always check the result before using it.
javascript
const text = "apple banana cherry"; // Wrong: missing 'g' flag, returns only first match const wrong = text.match(/b\w+/); console.log(wrong); // ["banana"] // Right: with 'g' flag, returns all matches const right = text.match(/b\w+/g); console.log(right); // ["banana"] // Check for null when no matches const noMatch = text.match(/z\w+/g); if (noMatch === null) { console.log("No matches found."); }
Output
["banana"]
["banana"]
No matches found.
Quick Reference
- Returns: Array of matches or
nullif none found. - Use
gflag to get all matches, otherwise only first match is returned. - Case sensitivity: Regular expressions are case sensitive by default.
- Supports: Regular expressions with flags like
g,i(ignore case),m(multiline).
Key Takeaways
Use string.match(regexp) to find matches with regular expressions in strings.
Add the 'g' flag to get all matches, not just the first one.
Always check if match() returns null before using the result.
Regular expressions are case sensitive unless you use the 'i' flag.
match() returns an array of matches or null if no matches exist.