I personally do consider www
to be a subdomain, and in case of 'second-level'-domains (.co.uk
) I would in fact consider co
the domain name and whatever comes before it would be a subdomain.
Since that doesn't really answer your question, here's an approach solely based on your input (which you will modify once you find out 'second-level' domains (that list does not cover everything) are a lot harder to detect than you think).
function subdomain(host) {
var part = host.split('.').reverse(),
index = 0;
while (part[index].length === 2 || !index) {
++index;
}
++index;
return part.length > index && part[index] !== 'www' ? part[index] : '';
}
Working example
What this does is applying a very blunt rule that 'second-level'-domains always consist of 2x2 chars (co.uk
, co.in
, etc) and filter those, then skip to what is now thought to be the main domain name and skip that. If finally there is something on the index we have determined and it does not match 'www', you get it back.
This is merely an example to show you how difficult your question is, as it would require an up-to-date (as in actively maintained, curated) list of 'second-level'-domains or else you may fail.
The only thing I actually did take into consideration is that some.deep.nested.sub.domain.com
will give you sub
instead of some
.
(Also note that I did not actively prevent the ip from matching at all, it just so happens to match the 2x2 rule).
I'm very curious about the problem you are trying to solve by trying to isolate the subdomain, as in itself it does not have any meaning. I can think of situations where you'd like to display a 'nickname' of sorts based on a subdomain, but then I recon you'd know the patterns to expect. From a technical point of view, having only the subdomain would be useless.