Search code examples
jqueryhyperlinkinternal

jQuery: select all internal links EXCLUDING links to downloadable files


I'm using following piece of jQuery code to select all internal links ...

var siteURL = "http://" + top.location.host.toString();
var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

and it works just fine. The only problem i'm facing is that i don't want to select internal links which directly points to downloadable files (e.g. http://www.example.com/downloadable.pdf)

Extension could be anything (pdf, mp3, jpg, gif, webm ... etc)

Now question is, how to exclude such internal links from the above criteria?

Or if i use .not() function to exclude such links, question would be, how to select all internal links which directly points to such downloadable files?


Solution

  • A simple solution would be to use a filter or not with a regular expression to reject the links you don't want:

    var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");
    
    $internalLinks = $internalLinks.not(function () {
      return $(this).attr('href').match(/\.(pdf|mp3|jpg|jpeg|etc)$/i);
    });
    

    The opposite, assuming all of your "not downloadable" URLs end in .html or .htm, would be to filter for links with those extensions:

    $internalLinks = $internalLinks.filter(function () {
      return $(this).attr('href').match(/\.html?/);
    });