Javascript location.host without www

If you want to get only the second- and top-level-domains, not any subdomains, this should help you:

var url = location.host; // e.g. "www.example.com"
return url.split(".").slice(-2).join("."); // "example.com"

This also works for other subdomains and even for more-than-threeleveldomains.


location.host.replace('http://www.','')

or (if you want to keep the http://)

location.host.replace('http://www.','http://')

It makes sure you only replace www if it is at the beginning.


For your first... you could modify the host:

location.host.replace('www.','')

Edit: address concerns

Having been down-voted again, and seeing lots of up-votes on the first comment, I will attempt to address concern about subdomains besides www that contain www...

Still steering clear of regex for this solution, mostly because generally it is harder to maintain regex, and there are a lot of developers who just don't touch regex at all...

var cleaned_host;
if(location.host.indexOf('www.') === 0){
    cleaned_host = location.host.replace('www.','');
}
// do something with `cleaned_host`

... or more succinctly ...

location.host.indexOf('www.') && location.host || location.host.replace('www.', '');
// evaluates to hostname with starting `www.` removed

Tags:

Javascript