Non-capturing groups in JavaScript regexes
The parentheses ( )
perform two
functions - character grouping and a
capturing group function. But what if
we need to group, but not put in our
capturing group? To solve this problem,
special non-capturing parentheses
(?: )
were came up - they group,
but don't put in a capturing group.
Example
In the following example, we need the first parentheses pair for grouping, and the second one for a capturing group. However, both parentheses pairs put data to the capturing group:
let str = 'abab123';
let res = str.match(/(ab)+([1-9]+)/);
As a result, in our capturing groups will be the following:
console.log(res[0]); // shows 'abab123'
console.log(res[1]); // shows 'ab'
console.log(res[2]); // shows '123'
Example
Let's make the first pair of parentheses only group, but not put to the capturing group:
let str = 'abab123';
let res = str.match(/(?:ab)+([1-9]+)/);
As a result, our number will be in the first capturing group:
console.log(res[1]); // shows '123'