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.
Practical example
// ONLINE-RUNNER:browser;
const getDomain = (url) => {
const instance = new URL(url);
const host = instance.hostname;
return host.startsWith('www.') ? host.substring(4) : host;
};
// Usage example:
console.log(getDomain('https://dirask.com')); // dirask.com
console.log(getDomain('https://dirask.com/about')); // dirask.com
console.log(getDomain('https://www.dirask.com')); // dirask.com
console.log(getDomain('https://www.dirask.com/about')); // dirask.com
Alternative solution 1
// ONLINE-RUNNER:browser;
const EXPRESSION = /^[a-z]+:\/\/(?:www\.)?([^:?#/]+)/; // domain in group expression
const getDomain = (url) => {
const match = EXPRESSION.exec(url);
if (match) {
return match[1];
}
return null;
};
// Usage example:
console.log(getDomain('https://dirask.com')); // dirask.com
console.log(getDomain('https://dirask.com/about')); // dirask.com
console.log(getDomain('https://www.dirask.com')); // dirask.com
console.log(getDomain('https://www.dirask.com/about')); // dirask.com
Alternative solution 2
// ONLINE-RUNNER:browser;
const EXPRESSION = /^[a-z]+:\/\/([^:?#/]+)/; // domain in group expression
const hasPrefix = (text, prefix) => {
if (prefix.length > text.length) {
return false;
}
for (let i = 0; i < prefix.length; ++i) {
if (text[i] !== prefix[i]) {
return false;
}
}
return true;
};
const getDomain = (url) => {
const match = EXPRESSION.exec(url);
if (match) {
const host = match[1];
if (hasPrefix(host, 'www.')) {
return host.substring(4);
}
return host;
}
return null;
};
// Usage example:
console.log(getDomain('https://dirask.com')); // dirask.com
console.log(getDomain('https://dirask.com/about')); // dirask.com
console.log(getDomain('https://www.dirask.com')); // dirask.com
console.log(getDomain('https://www.dirask.com/about')); // dirask.com