39

I am having the URL http://somesubdomain.domain.com (subdomains may vary, domain is always the same). Need to take subdomain and reload the page with something like domain.com/some/path/here/somesubdomain using greasemonkey (or open a new window with URL domain.com/some/path/here/somesubdomain, whatever).

6 Answers6

59
var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
Derek Swingley
  • 8,734
  • 5
  • 32
  • 33
  • 33
    What if the domain is google.co.uk? This will return the wrong subdomain. – TLK Dec 17 '12 at 07:54
  • 8
    To get only subdomain: window.location.host.split('.')[0]; – Philip Enc Feb 18 '16 at 13:26
  • 1
    @TLK is right, and Philip's solution only works if the subdomain always contains no dots. Sometimes subdomains have dots in them, making sub-subdomains, etc. I've provided a more complete (and much more painful, sadly) solution below. – jlbang Apr 14 '16 at 15:15
  • 2
    @TLK Yep, and if domain is "sub1.sub2.domain.com" it will be also wrong – acidernt Jul 05 '17 at 10:16
26

The answer provided by Derek will work in the most common cases, but will not work for "xxx.xxx" sub domains, or "host.co.uk". (also, using window.location.host, will also retrieve the port number, which is not treated : http://www.w3schools.com/jsref/prop_loc_host.asp)

To be honest I do not see a perfect solution for this problem. Personally, I've created a method for host name splitting which I use very often because it covers a larger number of host names.

This method splits the hostname into {domain: "", type: "", subdomain: ""}

function splitHostname() {
        var result = {};
        var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$');
        var urlParts = regexParse.exec(window.location.hostname);
        result.domain = urlParts[1];
        result.type = urlParts[2];
        result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);;
        return result;
}

console.log(splitHostname());

This method only returns the subdomain as a string:

function getSubdomain(hostname) {
        var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$');
        var urlParts = regexParse.exec(hostname);
        return hostname.replace(urlParts[0],'').slice(0, -1);
}

console.log(getSubdomain(window.location.hostname));
// for use in node with express:  getSubdomain(req.hostname)

These two methods will work for most common domains (including co.uk) NOTE: the slice at the end of sub domains is to remove the extra dot.

I hope this solves your problem.

Bamieh
  • 10,358
  • 4
  • 31
  • 52
Vlad Filip
  • 391
  • 4
  • 8
  • 1
    I used the Dereks solution and got into trouble when I suddenly didn't have a subdomain. Vlads answer works better in my case. – MartinJH Feb 26 '18 at 12:12
  • The 100% exact answer is the answer of jlbang on this page. Filip's anwser is smaller footprint, but pretty incomplete. However, a small footprint, though more complete one is given by sidanmor here: https://stackoverflow.com/questions/9752963/get-domain-name-without-subdomains-using-javascript – e-motiv Jul 01 '18 at 15:50
4

The solutions provided here work some of the time, or even most of the time, but not everywhere. To the best of my knowledge, the best way to find the full subdomain of any domain (and remember, sometimes subdomains have periods in them too! You can have sub-subdomains, etc) is to use the Public Suffix List, which is maintained by Mozilla.

The part of the URL that isn't in the Public Suffix List is the subdomain plus the domain itself, joined by a dot. Once you remove the public suffix, you can remove the domain and have just the subdomain left by removing the last segment between the dots.

Let's look at a complicated example. Say you're testing sub.sub.example.pvt.k12.ma.us. pvt.k12.ma.us is a public suffix, believe it or not! So if you used the Public Suffix List, you'd be able to quickly turn that into sub.sub.example by removing the known suffix. Then you could go from sub.sub.example to just sub.sub after stripping off the last portion of the remaining pieces, which was the domain. sub.sub is your subdomain.

jlbang
  • 1,226
  • 12
  • 14
  • The only drawback of using this list is it requires Mozilla to discover the domains and curate their list. It could be used as a first pass in an algorithm that then resorts to one of the other more naive methods if no match is found. – crush Apr 03 '18 at 20:56
  • 1
    @crush, I agree, that's a problem. However, given that the list is used in Firefox, Chrome, Opera and Internet Explorer (as explained on [the Learn page of that site](https://publicsuffix.org/learn/)) I'm pretty confident it is maintained pretty well. At worst, a very odd edge case could temporarily fall through. – jlbang Apr 04 '18 at 00:48
  • 1
    Interesting resource! Any idea if this list will be updated with the new GTLDs as well? Also, did not know the process is so arbitrary - any registrar can choose to delegate any tld as top level. – workwise Nov 15 '19 at 06:33
0

This could work in most cases except for the one that @jlbang mention

const split=location.host.split(".");
let subdomain="";
let domain="";
if(split.length==1){//localHost
  domain=split[0];
}else if(split.length==2){//sub.localHost or example.com
  if(split[1].includes("localhost")){//sub.localHost
    domain=split[1];
    subdomain=split[0];
  }else{//example.com
    domain=split.join(".");
  }
}else{//sub2.sub.localHost or sub2.sub.example.com or sub.example.com or example.com.ec sub.example.com.ec or  ... etc
  const last=split[split.length-1];
  const lastLast=split[split.length-2];
  if(last.includes("localhost")){//sub2.sub.localHost
    domain=last;
    subdomain=split.slice(0,split.length-1).join(".");
  }else if(last.length==2 && lastLast.length<=3){//example.com.ec or sub.example.com.ec
    domain=split.slice(split.length-3,split.length).join(".");
    if(split.length>3){//sub.example.com.ec
      subdomain=split.slice(0,split.length-3).join(".");
    }
  }else{//sub2.sub.example.com
    domain=split.slice(split.length-2,split.length).join(".");
    subdomain=split.slice(0,split.length-2).join(".");
  }
}
const newUrl = 'http://example.com/some/path/here/' + subdomain
Community
  • 1
  • 1
John Balvin Arias
  • 2,632
  • 3
  • 26
  • 41
0

I adapted Vlad's solution in modern Typescript:

const splitHostname = (
    hostname: string
  ): { domain: string; type: string; subdomain: string } | undefined => {
    var urlParts = /([a-z-0-9]{2,63}).([a-z.]{2,5})$/.exec(hostname);
    if (!urlParts) return;
    const [, domain, type] = urlParts;
    const subdomain = hostname.replace(`${domain}.${type}`, "").slice(0, -1);
    return {
      domain,
      type,
      subdomain,
    };
  };
Baptiste Arnaud
  • 2,522
  • 3
  • 25
  • 55
0

get a subdomain from URL

function getSubdomain(url) {
url = url.replace( "https://www.","");
url = url.replace( "http://www.","");
url = url.replace( "https://","");
url = url.replace("http://", "");
var temp = url.split("/");
if (temp.length > 0) {
    var temp2 = temp[0].split(".");
    if (temp2.length > 2) {
        return temp2[0];
    }
    else {
        return "";
    }
}
return "";

}

javed
  • 406
  • 3
  • 10