match() JavaScript String Method Explained
Whenever you use match() on a string, the method does the following:
- It creates a new array.
- It populates the newly created array with the patterns that match the method's regular expression argument.
match()
is sometimes written as String.prototype.match()
because it is a method of the String
object's prototype
property.
Syntax of the match()
Method
match()
accepts a regular expression argument. Here is the syntax:
string.match(RegExp);
- Suppose
match()
's argument is a non-RegExp
value—such as a string or a number. In that case, JavaScript will use thenew RegExp(...)
syntax to convert the argument to a regular expression. - If you do not provide an argument, the computer will return an array containing an empty string:
[""]
. null
returns if the regular expression argument does not match any pattern.
Example 1: Match the First day
Pattern
"SunDay, Tuesday, and Friday are good DAYS".match(/day/);
// The invocation above will return:
["day"];
Example 2: Match the First Case-Insensitive day
Pattern
"SunDay, Tuesday, and Friday are good DAYS".match(/day/i);
// The invocation above will return:
["Day"];
Example 3: Do a Global Case-Insensitive Match of day
"SunDay, Tuesday, and Friday are good DAYS".match(/day/gi);
// The invocation above will return:
["Day", "day", "day", "DAY"];
Important Stuff to Know about the match()
Method
Whenever you use a global flag (g
) with match()
's RegExp argument, the computer will ignore any capturing group in the regular expression.
For instance, the snippet below matched the first (\w+)d(a)y
pattern while also returning the matched capture groups' text: 'Tues'
and 'a'
.
"SunDay, Tuesday, and Friday are good DAYS".match(/(\w+)d(a)y/);
// The invocation above will return:
['Tuesday', 'Tues', 'a', index: 8, input: 'SunDay, Tuesday, and Friday are good DAYS', groups: undefined]
However, if you add a global flag to the regular expression, the computer will ignore the capture groups.
Here's an example:
"SunDay, Tuesday, and Friday are good DAYS".match(/(\w+)d(a)y/g);
// The invocation above will return:
["Tuesday", "Friday"];
Use matchAll()
to gain better access to capturing groups.
Overview
match()
creates a new array containing all the patterns that match the method's regular expression argument.