Consider the following example:
Here is the result:
.jpg .jpg,.jpg .jpg
I expect this result:
.jpg .jpg .jpg
Why placing parenthesis around the regular expression changes the result? Why using 'g' modifier changes again the result?
.match() function returns an array.
document.write() printed the array as a string.
When you captured a group in the string it makes an Array like this:
Array(  => 'the complete matched string',  => 'the first captured group',  => 'the second captured group', [.] => '...' )
So with your regex it becomes:
Array(  => '.jpg', // You match .jpg of the string  => '.jpg' // You captured the .jpg match )
And if you print an array it places a
, between the values.
If the regular expression does not include the
gflag, returns the same result as
RegExp.prototype.exec documentation [MDN] says:
The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
So as you introduced a capture group in the second expression, the first element is the whole match and the second contains the content of the capture group, which, in your example, is the whole match as well.
The first expression does not have a capture group, so you only get back the match.
Back to the
If the regular expression includes the
gflag, the method returns an Array containing all matches. If there were no matches, the method returns
g modifier, only matches are returned, but not the content of capture groups. In your string there is only one match.
©2020 All rights reserved.