I have the following code which I use to match fancybox 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
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
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 bothsflkj.JPG
andlkjfsl.jpg
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.
A couple of things.
Match accepts an object of
RegExp
, not a string. It may work in some browsers, but is definitely not standard.Without the strings
Also, you would want to check these at the end of a filename, instead of anywhere in the string.
Only searching at the end of string with $ suffix
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?