Without any hesitation I give you the EASIEST way to test for an external link with JavaScript!
function isExternal(link) { return link.hostname === window.location.hostname; } // Usage: var myLink = document.getElementById('my-link'); alert( isExternal(myLink) ); |
No regular expressions, no string operations, nothing! So simple!
The ‘hostname’ property is inherent of all links within a page (plus the location property of the window object). Sometimes you want to test an actual URL string instead of just a specific link; if so, then you’ll need to expand the function a little:
function isExternal(url) { var tempLink = document.createElement('a'); tempLink.href = url; return tempLink.hostname === window.location.hostname; } // Usage: alert( isExternal('https://j11y.io') ); |
How ridiculously simple is that!?
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
I guess it’s personal preference, but I like the terseness of Regular Expressions:
Pete, Regex may be a little more concise but it won’t work if you use absolute URLs for internal links…
Hi James,
I love your snippets – this one is another beauty! Personally I don’t like using large frameworks because of the overhaed and all the stuff you need to learn but are not really interested in …
So, keep on bringing on the snippets! 😉