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


  1. Won't this fail for domains like ?

  2. Thanks, Carl. Indeed this code needs a fix. Coming soon ...

  3. As a shorter alternative you can use a regular expression, something like:

    function getTLD() {
    return window.location.hostname.match(/[a-z]{2,}$/)[0] || 'Failure'


Comment Form Message