⊗jsSpREMP 121 of 281 menu

Capturing groups in the regex match method in JavaScript

As you already know, the substring found through the match method gets into the zero element of the resulting array. The remaining elements of this array include the so-called capturing groups.

Capturing groups are a way to split the found into separate parts. To use them, you need to enclose part of the regex in parentheses. In this case, in the resulting array, in addition to the found string, there will also be something that matched with the regex in these parentheses.

Let's try it in practice. Suppose we have such a string with time:

let str = '12:34';

Let's put the hours and minutes from this time in separate capturing groups:

let res = str.match(/(\d+):(\d+)/);

Let's look at the result:

console.log(res[0]); // '12:34' - matched string console.log(res[1]); // '12' - 1st capturing group console.log(res[2]); // '34' - 2nd capturing group

Given a string containing a domain:

let str = 'sss domain.ru zzz';

Find that domain and put its name in the first capturing group and a zone in the second.

Given a string containing a date:

let str = '31.12.2025';

Put a day in the first capturing group, a month in the second, and a year in the third.

enru