Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a link is an image

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)

like image 334
laggingreflex Avatar asked Oct 16 '13 04:10

laggingreflex


2 Answers

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

like image 43
mavrosxristoforos Avatar answered Oct 26 '22 19:10

mavrosxristoforos


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:

  • http://jsfiddle.net/fMCFB/1/
like image 57
Michael Zaporozhets Avatar answered Oct 26 '22 19:10

Michael Zaporozhets