Test if links are external with jQuery / javascript?

后端 未结 13 1337
囚心锁ツ
囚心锁ツ 2020-11-28 05:00

How do I test to see if links are external or internal? Please note:

  1. I cannot hard code the local domain.
  2. I cannot test for \"http\". I could just as
13条回答
  •  粉色の甜心
    2020-11-28 05:47

    You forgot one, what if you use a relative path.

    forexample: /test

            hostname = new RegExp(location.host);
                // Act on each link
                $('a').each(function(){
    
                // Store current link's url
                var url = $(this).attr("href");
    
                // Test if current host (domain) is in it
                if(hostname.test(url)){
                   // If it's local...
                   $(this).addClass('local');
                }
                else if(url.slice(0, 1) == "/"){
                    $(this).addClass('local'); 
                }
                else if(url.slice(0, 1) == "#"){
                    // It's an anchor link
                    $(this).addClass('anchor'); 
                }
                else {
                   // a link that does not contain the current host
                   $(this).addClass('external');                        
                }
            });
    

    There are also the issue of file downloads .zip (local en external) which could use the classes "local download" or "external download". But didn't found a solution for it yet.

提交回复
热议问题