Thursday, 8 May 2014

Extract Top-Level-Domain from a URL using client-side JavaScript


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