Skip to content
Announcing the new Pro Zone. Check it out!

match() JavaScript String Method Explained

Whenever you use match() on a string, the method does the following:

  1. It creates a new array.
  2. 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"];

Try it on StackBlitz

CodeSweetly ads

Express Your Love for Coding!

Explore CodeSweetly's Shop for an array of stylish products to enhance your coding experience.
Shop now

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"];

Try it on StackBlitz

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"];

Try it on StackBlitz

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"];