The Snippet
This is a small little snippet that extends the jQuery functionality to allow you to test whether a URL is external or internal with a special jQuery method: isExternal()
. It can tell whether absolute URLs are internal, but it doesn’t work on relative URLs.
$.fn.isExternal = function() { var host = new RegExp('/' + window.location.host + '/'); var link = 'http://' + window.location.host + this.attr('href'); return !host.test(link); };
Usage
$('a').isExternal()
Improved Method
This improved method for checking if a URL is external works on relative URLs as well. It’s much cleaner, without the need for regex. The magic is in creating a new anchor element and setting the link that we’re testing as it’s JavaScript href attribute. This allows us to access that object’s hostname property. Then we compare directly to the current page’s domain which can be retrieved using window.location.host
.
$.fn.isExternal = function() { var host = window.location.host; var link = $('<a>', { href: this.attr('href') })[0].host; return (link !== host); };
Credit for the idea of creating a temporary anchor element: http://tutorialzine.com/2013/07/quick-tip-parse-urls/
Test It Out
JavaScript Only Solution (No jQuery)
function is_external(link) { return (link.host !== window.location.host); } is_external(document.querySelector('a'));
It works fine to me! Thank’s to share this 😉
I’m happy you found it useful. Thanks for the feedback!
You saved my day, thanks so much 🙂
$.fn.isExternal is great, except that it is wrong.
[0].hostname; only returns the hostname, which is great unless you’re using a port, like many developers are when testing locally and of course sometimes out in the wild also. It needs to be replaced with [0].host;