views:

31

answers:

2

I have the following (jquery) selector looking for external links.

This works, and ignores all links that include location.hostname (e.g. www.domain.com)

My question is, how to extend this to also ignore links to subdomains of your site? (e.g. new.domain.com)

$('a').each(function() {

    var href = $(this).attr('href');

    if(this.hostname && this.hostname !== location.hostname) 
    {    
        $(this)
            .removeAttr('target')
            .attr('rel', 'external')                
            .attr('title', href)
            .click(function() {
                window.open($(this).attr('href'));
                return false;
            });
        }
});
A: 

Well if you know what your subdomains look like with respect to your site's hostname, you could just make a regex out of that. For example, if your hostnames are always x.y.z then you could split off the last two pieces of the hostname and ignore any anchors whose hostname ends the same way.

var parts = location.hostname.split('.'),
   domainMatch = new RegExp('[^.]*\\.' + parts[1] + '\\.' + parts[2] + '$');

if (this.hostname && !domainMatch.test(this.hostname)) {
 // ...
}
Pointy
You might also want to verify the length of the parts array. It could be the case that the domain only consists of `domain.com`.
cmptrgeekken
Yes definitely; like I said, it depends on the setup for the domain in question. It might be pretty hard to make a script that could work for any domain/subdomain family.
Pointy
+2  A: 
$('a').filter(function() {      
        return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1
      })
Sam Dark