0
0
JavascriptComparisonBeginner · 3 min read

Regex test vs match in JavaScript: Key Differences and Usage

In JavaScript, 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.

AspectRegExp.test()String.match()
TypeMethod of RegExp objectMethod of String object
Return ValueBoolean (true/false)Array of matches or null
PurposeCheck if pattern existsRetrieve matched text
Multiple MatchesNo, only tests existenceYes, 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".

javascript
const regex = /cat/;
const str = "The cat is sleeping.";
const result = regex.test(str);
console.log(result);
Output
true
↔️

String.match() Equivalent

Here is how you use match() to find the word "cat" in the same string.

javascript
const str = "The cat is sleeping.";
const matches = str.match(/cat/);
console.log(matches);
Output
[ 'cat', index: 4, input: 'The cat is sleeping.', groups: undefined ]
🎯

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.
Use 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.