2013-10-16 68 views
2

我需要检查URL是否为图片。检查链接是否为图片

答案here

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

提出在我的(特殊)情况下,假阳性时,有在非图像URL

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

(PS扩展:不能使用jquery,只有javascript /正则表达式)

回答

3

也许你可以在正则表达式之前加上一个点.,例如:

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

这会尝试在URL中匹配.jpg,.gif.png
您提到的正则表达式虽然尝试仅在URL末尾搜索jpggifpng,所以我不确定它是如何匹配的http://www.example.com/jpg/bpgpage/

如果ommit点.不过,它仍然会匹配http://www.example.com/jpg

+1

这里的美元符号意味着它只能在URL的END处找到扩展名,所以它不会匹配任何包含其中的扩展名的URL。 –

+0

我知道,但它仍然会匹配作为目录的“http:// www.example.com/jpg”。 – mavrosxristoforos

+0

我错过了我的代码中的'$'。 x_x – laggingreflex

-1

为什么不使用SUBSTR拉最后三个字符?

url.substr(url.length-3, 3); 
+2

那个uri:http://meow.com/kitten.png?somehorribleparameter=1 – dino

0

这里就是我会做,其中“海峡”是你匹配的字符串:

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

前提是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; 
    } 
} 

+0

好的。尽管如此,我会在分割点之前删除'?'部分。 – mavrosxristoforos

+0

@mavrosxristoforos哈哈是我在示例中做到了,现在在答案代码中进行更新;) –

1

// 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)