This regular expression fails in Firefox but works in IE.
function validate(x) {
return /.(jpeg|jpg)$/ig.test(x);
}
Can anybody explain why?
This regular expression fails in Firefox but works in IE.
function validate(x) {
return /.(jpeg|jpg)$/ig.test(x);
}
Can anybody explain why?
In regex expressions, "." by itself means "any character". Did you mean "\." to mean "period"?
The function is using a regular expression pattern .(jpeg|jpg)$
to test strings. It looks like the intent is to validate filenames to make sure they have an extension of either jpg
or jpeg
.
As James Bailey pointed out, there is an error in that the period should be escaped with a backslash. A period in a regular expression will match any character. So, as shown, the pattern would match both imagexjpg
and image.jpg
.
If you are testing with just the filename, then setting the 'g' flag for greedy doesn't make much sense since you are matching at the end of the string anyway - i ran the following:
function validate(x) {
return /\.(jpeg|jpg)$/i.test(x);
}
var imagename = 'blah.jpg';
alert (validate(imagename)); // should be true
imagename = 'blah.jpeg';
alert (validate(imagename)); // should be true
imagename = 'blah.png';
alert (validate(imagename)); // should be false
all three tests came out as expected in FF.
As for 'how it works' - regular expressions can get quite tricky - but I will explain the details of the above pattern:
so..
/\.(jpeg|jpg)$/i
means "a string ending in either .jpeg or .jpg - ignoring case"
so... .JPEG, .jpg, .JpeG, etc... will all pass now...