Regex test vs match in JavaScript: Key Differences and Usage
test() is a method of RegExp that returns true or false to check if a pattern exists in a string. match() is a String method that returns the matched substring(s) or null if no match is found.Quick Comparison
This table summarizes the main differences between test() and match() in JavaScript regex usage.
| Aspect | RegExp.test() | String.match() |
|---|---|---|
| Type | Method of RegExp object | Method of String object |
| Return Value | Boolean (true/false) | Array of matches or null |
| Purpose | Check if pattern exists | Retrieve matched text |
| Multiple Matches | No, only tests existence | Yes, if global flag is used |
| Usage Example | `/abc/.test(str)` | `str.match(/abc/)` |
Key Differences
test() is a method you call on a regular expression object. It simply tells you if the pattern exists anywhere in the string by returning true or false. It does not give you the actual matched text.
On the other hand, match() is a method you call on a string. It returns an array containing the matched substring(s) if the pattern is found, or null if not. If the regular expression has the global flag g, match() returns all matches; otherwise, it returns details about the first match.
Another difference is that test() is generally faster when you only need to check for existence, while match() is useful when you want to extract the matched parts from the string.
Code Comparison
Here is how you use test() to check if a string contains the word "cat".
const regex = /cat/; const str = "The cat is sleeping."; const result = regex.test(str); console.log(result);
String.match() Equivalent
Here is how you use match() to find the word "cat" in the same string.
const str = "The cat is sleeping."; const matches = str.match(/cat/); console.log(matches);
When to Use Which
Choose test() when you only need to know if a pattern exists in a string, as it returns a simple true or false and is efficient.
Choose match() when you want to extract the matched text or all matches from the string, especially if you need details about the match or multiple matches.
Key Takeaways
test() returns a boolean indicating if the pattern exists in the string.match() returns the matched substring(s) or null if no match is found.test() for quick existence checks and match() to get matched text.match() supports global matching with the g flag to find all matches.test() is a RegExp method; match() is a String method.