Test if links are external with jQuery / javascript?

后端 未结 13 1395
囚心锁ツ
囚心锁ツ 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:41

    Here's a jQuery selector for only external links:

    $('a[href^="(http:|https:)?//"])') 
    

    A jQuery selector only for internal links (not including hash links within the same page) needs to be a bit more complicated:

    $('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])')
    

    Additional filters can be placed inside the :not() condition and separated by additional commas as needed.

    http://jsfiddle.net/mblase75/Pavg2/


    Alternatively, we can filter internal links using the vanilla JavaScript href property, which is always an absolute URL:

    $('a').filter( function(i,el) {
        return el.href.indexOf(location.protocol+'//'+location.hostname)===0;
    })
    

    http://jsfiddle.net/mblase75/7z6EV/

提交回复
热议问题