javascript - 检查链接是否为图片

标签 javascript regex image url

我需要检查一个 URL 是否是一个图像。

答案here

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

当非图像 URL 中有扩展名时,在我的(特殊)情况下会引发误报

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

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

最佳答案

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

示例:

关于javascript - 检查链接是否为图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19395458/

相关文章:

html - 如何创建可缩放的水平和垂直图像?

javascript - 工厂内 promise , promise 完成前返回

regex - 只打印匹配正则表达式的部分

python - 从文本中删除正则表达式数字

python - 将包含 2 个值的列拆分为 pandas df 中的不同列

javascript - 仅使用 JavaScript 延迟图像并不能消除 PageSpeed 警告

html - 如何使用 CSS 将 "crop"矩形图像变成正方形?

JavaScript - If 语句始终返回 true

javascript - 在 javascript 中使用闭包时出现类型错误

javascript - VS代码: "Go to definition" from JS url (view url) to the Django view