I have next JS-code:
var str = 'some string';
var rexp = /^([^#]+)/;
var matchArr = str.match(rexp);
matchArr then contains two items matchArr[0] = ‘some string’ and
matchArr[1] = ‘some string’; Whereas I’m expecting the array with only one item.
I can’t understand this behavior. When I remove parentheses, then matchArr contains only one match. Why this happens, does anybody can explain?
When you use capturing parentheses in your regular expression, it adds an item to the returned results array for the overall match and each set of capturing parentheses.
matchArr[0]is everything that was matched.matchArr[1]is what matches in the first set of capturing parenthesesmatchArr[2]is what matches in the second set of capturing parenthesesand so on
So, in your regex
/^([^#]+)/, there is no difference betweenmatchArr[0]andmatchArr[1]because everything that matches is in the capturing parentheses.If you did this:
You would find that:
because there are parts of the match that are not in the capturing parentheses.
Or if you did this:
You would find that: