Languages
[Edit]
EN

JavaScript - get domain name from given URL

8 points
Created by:
May87
827

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

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join