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:
xxxxxxxxxx
1
const ORIGIN_EXPRESSION = /^https?:\/\/[^/?#]+/i;
2
3
const compareStrings = (a, b) => a.toLowerCase() === b.toLowerCase();
4
5
const isInternal = (url, origin = location.origin) => {
6
if (url == null) { // null or undefined
7
return false;
8
}
9
if (url === '') {
10
return true;
11
}
12
const match = url.match(ORIGIN_EXPRESSION);
13
if (match) {
14
return compareStrings(origin, match[0]); // web page origin === indicated url origin
15
}
16
return true;
17
};
18
19
20
// Usage example:
21
22
console.log(isInternal('')); // true
23
console.log(isInternal('/snippets')); // true
24
console.log(isInternal('?parameter=value')); // true
25
console.log(isInternal('#anchor')); // true
26
console.log(isInternal('robots.txt')); // true
27
console.log(isInternal('/path/to/file.txt')); // true
28
29
console.log(isInternal('https://dirask.com')); // true
30
console.log(isInternal('https://dirask.com/snippets')); // true
31
32
console.log(isInternal('https://google.com')); // false
33
console.log(isInternal('https://google.com/about')); // false
Note: the solution uses
location.origin
property that is available in web browsers only.
Note: in the above example, URLs are tested as internal, according to the current origin - Dirask origin.
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:
xxxxxxxxxx
1
const diraskOrigin = 'https://dirask.com';
2
3
console.log(isExternal('https://dirask.com', diraskOrigin)); // true
4
console.log(isExternal('https://dirask.com/snippets', diraskOrigin)); // true
5
6
7
const googleOrigin = 'https://google.com';
8
9
console.log(isExternal('https://google.com', googleOrigin)); // true
10
console.log(isExternal('https://google.com/about', googleOrigin)); // true