EN
JavaScript - check if URL is internal
9
points
In this short article, we would like to show how to use JavaScript, to check if URL is internal.
As an internal URL we understand the URL that indicates some webpage or resource on the same website on what was placed.
Practical example:
// ONLINE-RUNNER:browser;
const ORIGIN_EXPRESSION = /^https?:\/\/[^/?#]+/i;
const compareStrings = (a, b) => a.toLowerCase() === b.toLowerCase();
const isInternal = (url, origin = location.origin) => {
if (url == null) { // null or undefined
return false;
}
if (url === '') {
return true;
}
const match = url.match(ORIGIN_EXPRESSION);
if (match) {
return compareStrings(origin, match[0]); // web page origin === indicated url origin
}
return true;
};
// Usage example:
console.log(isInternal('')); // true
console.log(isInternal('/snippets')); // true
console.log(isInternal('?parameter=value')); // true
console.log(isInternal('#anchor')); // true
console.log(isInternal('robots.txt')); // true
console.log(isInternal('/path/to/file.txt')); // true
console.log(isInternal('https://dirask.com')); // true
console.log(isInternal('https://dirask.com/snippets')); // true
console.log(isInternal('https://google.com')); // false
console.log(isInternal('https://google.com/about')); // false
Note: the solution uses
location.originproperty that is available in web browsers only.
Note: in the above example, URLs are tested as internal, according to the current origin - Dirask origin.
Custom origin cases
URL can be internal according to indicated origin.
It means:
- for https://google.com origin, all Google links will be internal,
- for https://dirask.com origin, all Dirask links will be internal,
Practical example:
const diraskOrigin = 'https://dirask.com';
console.log(isExternal('https://dirask.com', diraskOrigin)); // true
console.log(isExternal('https://dirask.com/snippets', diraskOrigin)); // true
const googleOrigin = 'https://google.com';
console.log(isExternal('https://google.com', googleOrigin)); // true
console.log(isExternal('https://google.com/about', googleOrigin)); // true