Check If Link Is External Using jQuery

By January 13, 2017June 14th, 2020Blog, Javascript, jQuery
Allure Web Solutions Code Snippet

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

Test if link is external or internal

JavaScript Only Solution (No jQuery)

function is_external(link) {
return (link.host !== window.location.host);
}

is_external(document.querySelector('a'));
Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Join the discussion 4 Comments

Leave a Reply