0

I'm looking for a lightweight way to parse a URL and extract just the domain name. The URL may be different is certain cases but I would always like the same result, for instance:

www.mysite.com  --->   mysite
mysite.staging.blahblah.stuff.com:8080   --->  mysite
mysite.net  --->  mysite

'mysite' will always be part of the URL and would never have more than one dot before it.

flyagaricus
  • 119
  • 1
  • 2
  • 8

2 Answers2

1

You can use the location.host native javascript object to get the host portion of the url then you can pass that into a helper function to split it up on the period. The first item in the array produced by the split should be what you are looking for. However, if www is part of the url what you are looking for will be the second item.

 parseURL(location.host);

 function parseURL(host) {
     var hostParts = host.split(".");
     if (hostParts[0] == "www") {
         return hostParts[1];    
     }
     return hostParts[0];
}
Dropzilla
  • 502
  • 3
  • 14
0

Perhaps it would be better to reverse the problem -- check each of the possible values against the hostname:

for ( i = 0; i < sitenames.length; i++ ) {
    if ( location.host.indexOf(sitenames[i]) >= 0 ) {
        sitename = sitenames[i];
        break;
    }
}
nandhp
  • 4,680
  • 2
  • 30
  • 42