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!