JS/Jquery, Match not finding the PNG = match('/gif|jpg|jpeg|png/')
I have the following code which I use to match fancybo开发者_JS百科x possible elements:
$('a.grouped_elements').each(function(){
var elem = $(this);
// Convert everything to lower case to match smart
if(elem.attr('href').toLowerCase().match('/gif|jpg|jpeg|png/') != null) {
elem.fancybox();
}
});
It works great with JPGs but it isn't matching PNGs for some reason. Anyone see a bug with the code? Thanks
A couple of things.
Match accepts an object of RegExp
, not a string. It may work in some browsers, but is definitely not standard.
"gif".match('/gif|png|jpg/'); // null
Without the strings
"gif".match(/gif|png|jpg/); // ["gif"]
Also, you would want to check these at the end of a filename, instead of anywhere in the string.
"isthisagif.nope".match(/(gif|png|jpg|jpeg)/); // ["gif", "gif"]
Only searching at the end of string with $ suffix
"isthisagif.nope".match(/(gif|png|jpg|jpeg)$/); // null
No need to make href lowercase, just do a case insensitive search /i
.
Look for a dot before the image extension as an additional check.
And some tests. I don't know how you got any results back with using a string argument to .match
. What browser are you on?
I guess the fact that it'll match anywhere in the string (it would match "http://www.giftshop.com/" for instance) could be considered a bug. I'd use
/\.(gif|jpe?g|png)$/i
You are passing a string to the match() function rather than a regular expression. In JavaScript, strings are delimited with single quotes, and regular expressions are delimited with forward slashes. If you use both, you have a string, not a regex.
This worked perfectly for me: /.+\.(gif|png|jpe?g)$/i
.+
-> any string
\.
-> followed by a point.
(gif|png|jpe?g)
-> and then followed by any of these extensions. jpeg may or may not have the letter e.
$
-> now the end of the string it's expected
/i
-> case insensitive mode: matches both sflkj.JPG
and lkjfsl.jpg
精彩评论