Languages
[Edit]
EN

JavaScript - check if URL is external

9 points
Created by:
MindOfMadness3
696

In this short article, we would like to show how using JavaScript, to check if URL is external.

Practical example:

// ONLINE-RUNNER:browser;

const ORIGIN_EXPRESSION = /^https?:\/\/[^/?#]+/i;

const compareStrings = (a, b) => a.toLowerCase() === b.toLowerCase();

const isExternal = (url, origin = location.origin) => {
    if (url == null) { // null or undefined
        return false;
    }
    if (url === '') {
        return false;
    }
    const match = url.match(ORIGIN_EXPRESSION);
    if (match) {
        return !compareStrings(origin, match[0]); // web page origin !== indicated url origin
    }
    return false;
};


// Usage example:

console.log(isExternal(''));                   // false
console.log(isExternal('/snippets'));          // false
console.log(isExternal('?parameter=value'));   // false
console.log(isExternal('#anchor'));            // false
console.log(isExternal('robots.txt'));         // false
console.log(isExternal('/path/to/file.txt'));  // false

console.log(isExternal('https://dirask.com'));           // false
console.log(isExternal('https://dirask.com/snippets'));  // false

console.log(isExternal('https://google.com'));           // true
console.log(isExternal('https://google.com/about'));     // true

Note: the solution uses location.origin property that is available in web browsers only. 

Note: in the above example, URLs are tested as external, according to current origin - Dirask origin.

 

Custom origin cases

URL can be external according to indicated origin.

It means:

Practical example:

const googleOrigin = 'https://google.com';

console.log(isExternal('https://dirask.com', googleOrigin));           // true
console.log(isExternal('https://dirask.com/snippets', googleOrigin));  // true


const diraskOrigin = 'https://dirask.com';

console.log(isExternal('https://google.com', diraskOrigin));           // true
console.log(isExternal('https://google.com/about', diraskOrigin));     // true

 

See also

  1. JavaScript - check if URL is internal

Alternative titles

  1. JavaScript - check if link is external
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join