LB.
LB.

Reputation: 14112

How to get a subdomain using window.location?

If I have a hostname such as: http://sample.example.com and in Javascript I do window.location.hostname, would I get "example.com" or "sample.example.com"?

If not, how would I be able to get sample.example.com?

Upvotes: 38

Views: 67424

Answers (14)

Harsh Patel
Harsh Patel

Reputation: 1324

function getSubdomain(url) {
    try {
        // Create a URL object
        const parsedUrl = new URL(url);

        // Extract the hostname
        const hostname = parsedUrl.hostname;

        // Split the hostname into parts
        const parts = hostname.split('.');

        // Check if we have at least three parts (subdomain, domain, top-level domain)
        // console.log(parts, parts.length);
        if (parts.length < 3) {
            return null; // No subdomain present
        }

        // Remove the last two parts (domain and TLD)
        const subdomainParts = parts.slice(0, -2);

        // Join the remaining parts to form the subdomain
        return subdomainParts.join('.');
    } catch (e) {
        console.error('Invalid URL:', e);
        return null;
    }
}

console.log(getSubdomain('https://example.com/this-is-example'));
console.log(getSubdomain('https://test-sub.example.com/this-is-example'));
console.log(getSubdomain('https://abc1.hello.example.com/this-is-example'));
console.log(getSubdomain('https://abc1.test-sub.example.com/this-is-example'));

Upvotes: 0

TacoEater
TacoEater

Reputation: 2268

In my case I needed something a little more versaitile so I wrote this function:

const getSubdomainFromHref = href => {
  let a = href.replace("http://", "").replace("https://", "");
  subdomain = a.substring(0, a.indexOf("."));
  return subdomain || "default";
};

Upvotes: 0

feyzullahyildiz
feyzullahyildiz

Reputation: 667

Subdomain could have dots, splitting with dot is not valid. You can check this library https://www.npmjs.com/package/psl

These are valid subdomains.

www.example.com
www.foo.example.com
foo.bar.example.com

You can check it in your local machine if you have a server. This is working in my app http://dev.test.foo.localhost:3000

Upvotes: 0

KATHEESKUMAR
KATHEESKUMAR

Reputation: 177

It's a simple way to split domain parts like subdomain.maindomain.extension

// Print Subdomain
console.log(window.location.host.split('.')[0]);

// Print  Maindomain
console.log(window.location.host.split('.')[1]);

// Print  extension 
console.log(window.location.host.split('.')[2]);

Upvotes: 1

Master Morsy
Master Morsy

Reputation: 96

const subdomain = window.location.hostname.split(".")[0]

window.location.hostname return string include subdomain - main domain - ltd
so you can easily get the first word by converting it to an array then getting first item

Upvotes: 6

Rudin Swagerman
Rudin Swagerman

Reputation: 281

This does the trick for me:

var host = window.location.host
var subdomain = host.split('.')[0]

Upvotes: 28

tennisgent
tennisgent

Reputation: 14201

I know this is an old question but a more robust answer would be to capture all subdomains. It's possible to have nested subdomains such as https://my.company.website.com. In order to adequately capture all subdomains, I think this is the simplest answer:

// for https://my.company.website.com,
const subdomain = window.location.hostname.split('.').slice(0, -2).join('.');
console.log(subdomain); // "my.company"

Upvotes: 16

I recommend using the npm package psl (Public Suffix List). You can look this link: npm psl

Upvotes: 1

yue
yue

Reputation: 179

with array destructuring you can do this:

// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"

Upvotes: 1

It can be done as below:

var subdomain =  window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;

Upvotes: 12

Peter Bailey
Peter Bailey

Reputation: 105878

First of all, it's window.location, not document.location (document.location works in some browsers but it is not standard)

And yes, location.hostname will return the entire domain name, including any subdomains

Read more here

Window Location

Upvotes: 5

Marcin
Marcin

Reputation: 7994

How about this snippet. It might help:

var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);

Upvotes: 2

Al.
Al.

Reputation: 2872

Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.

Upvotes: 3

nickf
nickf

Reputation: 546035

Yes, window.location.hostname will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:

// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];

Upvotes: 31

Related Questions