EN
JavaScript - check if URL is external
9
points
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.originproperty 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:
- for https://google.com origin, all Dirask links will be external,
- for https://dirask.com origin, all Google links will be external,
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