How to Check If a String URL Refers to an External Link Using JavaScript?

By comparing the hostname of the string URL to the hostname of the web page URL, you can determine whether the link is external or not. In order to get the hostname from a string URL, perhaps the best way is to create a temporary HTMLAnchorElement and use the hostname property available on it. For example:

const isExternalLink = (url) => {
    const tmp = document.createElement('a');
    tmp.href = url;
    return tmp.host !== window.location.host;
};

// output: true
console.log(isExternalLink('https://foobar.com'));
console.log(isExternalLink('//foobar.com'));

// output: false
console.log(isExternalLink('https://www.designcise.com'));
console.log(isExternalLink('//www.designcise.com'));
console.log(isExternalLink('/foobar'));
console.log(isExternalLink('#foobar'));

The benefit of using this approach is that:

  • It would automatically resolve the hostname for relative paths and fragments;
  • It works with protocol-relative URLs (you should avoid them though).

To demonstrate this, let's look at the following examples:

const lnk = document.createElement('a');
lnk.href = '/foobar';

console.log(lnk.host); // output: 'www.designcise.com'
const lnk = document.createElement('a');
lnk.href = '#foobar';

console.log(lnk.host); // output: 'www.designcise.com'
const lnk = document.createElement('a');
lnk.href = '//www.designcise.com';

console.log(lnk.host); // output: 'www.designcise.com'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.