Consider the following example:
<html>
<body>
<script type="text/javascript">
var str="filename.jpg";
var pattOne = new RegExp('\.[^\.]*$');
var pattTwo = new RegExp('(\.[^\.]*$)');
var pattThree = new RegExp('(\.[^\.]*$)', 'g');
document.write(str.match(pattOne));
document.write('<br>');
document.write(str.match(pattTwo));
document.write('<br>');
document.write(str.match(pattThree));
</script>
</body>
</html>
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?
From
String.prototype.match[MDN]:Where the
RegExp.prototype.execdocumentation [MDN] says: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
matchdocumentation:With the
gmodifier, only matches are returned, but not the content of capture groups. In your string there is only one match.