检查链接是否是图像

时间:2013-10-16 04:49:18

标签: javascript regex image url

我需要检查网址是否为图片。

答案here

/(jpg|gif|png)$/.test(...
当非图像网址中存在扩展名时,

在我的(特殊)案例中引发误报

http://www.example.com/jpg/bpgpage/

(PS:不能使用jquery,只能使用javascript / regex)

6 个答案:

答案 0 :(得分:5)

如果uri以扩展名结尾,则每次都应该有效。

<强>代码:

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;   
    }
}

示例

答案 1 :(得分:3)

也许你可以在正则表达式之前添加一个点.,如下所示:

  /\.(jpg|gif|png)$/.test( ..

这会尝试在网址中匹配.jpg.gif.png 您提到的正则表达式确实尝试仅在网址末尾搜索jpggifpng,因此我不确定它是如何匹配的{{1} }。

如果您忽略点http://www.example.com/jpg/bpgpage/,它仍会匹配.

答案 2 :(得分:0)

这就是我要做的,其中“str”是你匹配的字符串:

return (str.match(/\.(jpg|gif|png)$/)!= null);

答案 3 :(得分:0)

// function for check the type of any source 
function checkExtension(file) {
    var extension = file.substr((file.lastIndexOf('.') + 1));
    switch (extension) {
    case 'jpg':
    case 'png':
    case 'gif':
        return "img" // There's was a typo in the example where
        break; // the alert ended with pdf instead of gif.
    case 'mp4':
    case 'mp3':
    case 'ogg':
        return "video"
        break;
    case 'html':
        return "html"
        break;
 
    }
};
var ex = checkExtension("if-a-link-is-an-image.png")
console.log(ex)
     

答案 4 :(得分:0)

您可以在内容类型标题中验证这里是一个函数示例:

nan

因此,这将查看内容类型是否以图像开头,则链接是根据此图像类型的图像: https://www.iana.org/assignments/media-types/media-types.xhtml#image

你可以测试一下:

async function verifyUrlImage(url){
try{
    let resp= $.ajax(url);
    await resp;
    let headers=resp.getAllResponseHeaders().split(/\n/g);
    for(let i=0;i<=headers.length;i++){
        let hd=headers[i].split(': ')
        if (hd[0]=='content-type' && hd[1].indexOf('image')==0)
           return true;
    }
}
catch{}
return false;
}

答案 5 :(得分:-1)

为什么不使用substr?

来拉最后三个字符
url.substr(url.length-3, 3);
相关问题