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?
The MATCH function searches for a specified item in a range of cells, and then returns the relative position of that item in the range. For example, if the range A1:A3 contains the values 5, 25, and 38, then the formula =MATCH(25,A1:A3,0) returns the number 2, because 25 is the second item in the range.
JavaScript String match() The match() method returns an array with the matches. The match() method returns null if no match is found.
match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.
Java - String matches() MethodThis method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).
From String.prototype.match
[MDN]:
If the regular expression does not include the
g
flag, returns the same result asregexp.exec(string)
.
Where the 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 match
documentation:
If the regular expression includes the
g
flag, the method returns an Array containing all matches. If there were no matches, the method returnsnull
.
With the g
modifier, only matches are returned, but not the content of capture groups. In your string there is only one match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With