Get subdomain and load it to url with greasemonkey

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.


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);