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

Learn how you can determine if a URL is external or internal

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'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.