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.
Syntax of the match()
Method
match()
accepts a regular expression argument. Here is the syntax:
string.match(RegExp);
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"];