JS/Jquery, Match not finding the PNG = match('

2019-05-18 08:52发布

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

4条回答
Emotional °昔
2楼-- · 2019-05-18 09:18

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
查看更多
Fickle 薄情
3楼-- · 2019-05-18 09:18

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

查看更多
欢心
4楼-- · 2019-05-18 09:27

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.

查看更多
甜甜的少女心
5楼-- · 2019-05-18 09:33

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?

查看更多
登录 后发表回答