Skip to content Skip to sidebar Skip to footer

Regex Expression Or Jquery Selector To Not Match "external" Links In Href

I have a jQuery plugin that overrides link behavior, to allow Ajax loading of page content. Simple enough with a delegated event like $(document).on('click','a', function(){});. bu

Solution 1:

I might use the selector:

$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"])')

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

Note that mailto: is correct, not mailto:// as in your original question.


In the interest of thoroughness, the following will also catch internal links that use absolute URLs (http://the-domain-you-are-on-now.com/whatever.html):

$('a:not([href*="://"],[target="_blank"],[href^="#"],[href^="mailto:"]),a[href^="'+location.protocol+'//'+location.hostname+'"]')

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

Solution 2:

I don't know why you voted down my last answer but on reference url you will find exact condition

var a = newRegExp('/' + window.location.host + '/');
     if(!a.test(this.href)){
     //do stuff when it an external link
     }
    else{
    // do stuff when it's internal link
    }

Here is reference http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/

Post a Comment for "Regex Expression Or Jquery Selector To Not Match "external" Links In Href"