EN
JavaScript - get domain name from given URL
8 points
In this article, we would like to show how to get a domain from a given URL in JavaScript.
xxxxxxxxxx
1
const getDomain = (url) => {
2
const instance = new URL(url);
3
const host = instance.hostname;
4
return host.startsWith('www.') ? host.substring(4) : host;
5
};
6
7
8
// Usage example:
9
10
console.log(getDomain('https://dirask.com')); // dirask.com
11
console.log(getDomain('https://dirask.com/about')); // dirask.com
12
console.log(getDomain('https://www.dirask.com')); // dirask.com
13
console.log(getDomain('https://www.dirask.com/about')); // dirask.com
xxxxxxxxxx
1
const EXPRESSION = /^[a-z]+:\/\/(?:www\.)?([^:?#/]+)/; // domain in group expression
2
3
const getDomain = (url) => {
4
const match = EXPRESSION.exec(url);
5
if (match) {
6
return match[1];
7
}
8
return null;
9
};
10
11
12
// Usage example:
13
14
console.log(getDomain('https://dirask.com')); // dirask.com
15
console.log(getDomain('https://dirask.com/about')); // dirask.com
16
console.log(getDomain('https://www.dirask.com')); // dirask.com
17
console.log(getDomain('https://www.dirask.com/about')); // dirask.com
xxxxxxxxxx
1
const EXPRESSION = /^[a-z]+:\/\/([^:?#/]+)/; // domain in group expression
2
3
const hasPrefix = (text, prefix) => {
4
if (prefix.length > text.length) {
5
return false;
6
}
7
for (let i = 0; i < prefix.length; ++i) {
8
if (text[i] !== prefix[i]) {
9
return false;
10
}
11
}
12
return true;
13
};
14
15
const getDomain = (url) => {
16
const match = EXPRESSION.exec(url);
17
if (match) {
18
const host = match[1];
19
if (hasPrefix(host, 'www.')) {
20
return host.substring(4);
21
}
22
return host;
23
}
24
return null;
25
};
26
27
28
// Usage example:
29
30
console.log(getDomain('https://dirask.com')); // dirask.com
31
console.log(getDomain('https://dirask.com/about')); // dirask.com
32
console.log(getDomain('https://www.dirask.com')); // dirask.com
33
console.log(getDomain('https://www.dirask.com/about')); // dirask.com