I need to check whether a URL is an image.
The answer here
/(jpg|gif|png)$/.test(...
raises a false positive in my (special) case when there's an extension in a non-image URL
http://www.example.com/jpg/bpgpage/
(PS: can't use jquery, only javascript/regex)
Maybe you can add a dot .
before the regular expression, as such:
/\.(jpg|gif|png)$/.test( ..
That will try to match .jpg
, .gif
and .png
in URLs.
The regular expression you mentioned though, does try to search for jpg
, gif
and png
only at the end of the URL, so I'm not sure how it matched http://www.example.com/jpg/bpgpage/
.
If you ommit the dot .
though, it will still match http://www.example.com/jpg
Provided that the uri ends with the extension, this should work every time.
Code:
var isUriImage = function(uri) {
//make sure we remove any nasty GET params
uri = uri.split('?')[0];
//moving on, split the uri into parts that had dots before them
var parts = uri.split('.');
//get the last part ( should be the extension )
var extension = parts[parts.length-1];
//define some image types to test against
var imageTypes = ['jpg','jpeg','tiff','png','gif','bmp'];
//check if the extension matches anything in the list.
if(imageTypes.indexOf(extension) !== -1) {
return true;
}
}
Example:
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