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('/' + + '/');
  var link = 'http://' + + this.attr('href');

  return !host.test(link);




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

$.fn.isExternal = function() {
  var host =;
  var link = $('<a>', {
    href: this.attr('href')

  return (link !== host);
Credit for the idea of creating a temporary anchor element:

Test It Out

Test if link is external or internal

JavaScript Only Solution (No jQuery)

function is_external(link) {
return ( !==;

Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Join the discussion 4 Comments

Leave a Reply