Skip to content

Instantly share code, notes, and snippets.

@uniqname
Created January 31, 2013 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uniqname/4683217 to your computer and use it in GitHub Desktop.
Save uniqname/4683217 to your computer and use it in GitHub Desktop.
Extension of location object to get the site name (of SLD, second level domain) of either the document's URL or from a given URL.
/*************
* Custom siteName functionality
* window.location.siteName reduces a either the documents url or a
* given url to the top most site name.
* i.e. photography.nataionalgeographic.com would return nationalgeographic.com,
* mysubdomain.mywebsite.co.uk would return mywebsite.co.uk.
***********/
if (typeof window.location.siteName === 'undefined') {
window.location.siteName = function (url) {
var hostName = url || window.location.hostname,
hostNamePosFromEnd;
//Don't want any http:// or similar stuff.
hostName = hostName.replace(/^\w+?:\d*?\/\//, '');
//Drop any path info from url.
hostName = hostName.split('/')[0];
hostName = hostName.split('.');
hostNamePosFromEnd = (hostName.length >= 2) ? ((hostName[hostName.length - 2].length === 2) ? 3 : 2) : 1;
while (hostName.length > hostNamePosFromEnd) {
hostName.shift();
}
return hostName.join('.');
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment