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:
xxxxxxxxxx
1
const ORIGIN_EXPRESSION = /^https?:\/\/[^/?#]+/i;
2
3
const compareStrings = (a, b) => a.toLowerCase() === b.toLowerCase();
4
5
const isExternal = (url, origin = location.origin) => {
6
if (url == null) { // null or undefined
7
return false;
8
}
9
if (url === '') {
10
return false;
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 false;
17
};
18
19
20
// Usage example:
21
22
console.log(isExternal('')); // false
23
console.log(isExternal('/snippets')); // false
24
console.log(isExternal('?parameter=value')); // false
25
console.log(isExternal('#anchor')); // false
26
console.log(isExternal('robots.txt')); // false
27
console.log(isExternal('/path/to/file.txt')); // false
28
29
console.log(isExternal('https://dirask.com')); // false
30
console.log(isExternal('https://dirask.com/snippets')); // false
31
32
console.log(isExternal('https://google.com')); // true
33
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.
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:
xxxxxxxxxx
1
const googleOrigin = 'https://google.com';
2
3
console.log(isExternal('https://dirask.com', googleOrigin)); // true
4
console.log(isExternal('https://dirask.com/snippets', googleOrigin)); // true
5
6
7
const diraskOrigin = 'https://dirask.com';
8
9
console.log(isExternal('https://google.com', diraskOrigin)); // true
10
console.log(isExternal('https://google.com/about', diraskOrigin)); // true