Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match external links with javascript (but ignore subdomains)?

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;
            });
        }
});
like image 754
meleyal Avatar asked Nov 27 '25 08:11

meleyal


1 Answers

$('a').filter(function() {      
        return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1
      })
like image 109
Sam Dark Avatar answered Nov 29 '25 22:11

Sam Dark