I needed a way to extract the top-level-domain from a url in a client-side javascript. I use the window.location object to achieve this (as I needed it in a CSJS anyway). There might be an easier way to do this, but this is my version of doing this:
/*
* This function returns the TLD part of the url based on window.location => CSJS
*/
function getTLD() {
var hostName = window.location.hostname;
var hostNameArray = hostName.split(".");
var posOfTld = hostNameArray.length - 1;
var tld = hostNameArray[posOfTld];
return tld;
}
Looking forward to your approacches to to this ;-)
Won't this fail for domains like .co.uk ?
ReplyDeleteThanks, Carl. Indeed this code needs a fix. Coming soon ...
ReplyDeleteAs a shorter alternative you can use a regular expression, something like:
ReplyDeletefunction getTLD() {
return window.location.hostname.match(/[a-z]{2,}$/)[0] || 'Failure'
}