Wednesday, January 21, 2009

How to get domain name from URL using javascript.

Use following javascript function to get domain name from URL.
function fnGetDomain(url) {
   return url.match(/:\/\/(.[^/]+)/)[1];
}

For ex: <script language="javascript">fnGetDomain("http://mail.google.com/mail/?source=navclient-ff");</script> will return "mail.google.com"

10 comments:

  1. very good function, thank you

    i added a little tweak to remove the 'www.' part

    function fnGetDomain(url) {
    return (url.match(/:\/\/(.[^/]+)/)[1]).replace('www.','');
    }

    ReplyDelete
  2. function getDomain(url)
    {
    return url.match(/:\/\/(www\.)?(.[^/:]+)/)[2];
    }

    ReplyDelete
  3. Excellent function utility! Thanks for the help :)

    ReplyDelete
  4. Hey, the result isn't domain, it's host of a url.

    for url (http://mail.google.com/mail/?xxxxx)
    its host is: mail.google.com
    but the domain is: google.com

    and others:
    http://www.google.co.ck/#hl=en&source=hp&biw=1440&bih=703&q=hello&aq=f&aqi=g10&aql=&oq=&fp=3ab7f9268f5901b
    its host is: www.google.co.ck
    but the domain is: google.co.ck

    Black.Lee

    ReplyDelete
  5. i have to use a website as a input.so i have to cluster the webpages for pattern analysis, so have to convert a web url into a number.... can u tell me how to extract the webpage info from url and convert into integer in JAVASCRIPT.. mail me at aloksalian@yahoo.com

    ReplyDelete
  6. Thanx a lot.

    ReplyDelete
  7. This solution take into account also the optional digit after the "www" (e.g. http://www2.ohchr.org/english):

    function getDomain(url) {
    return url.match(/:\/\/(www[0-9]?\.)?(.[^/:]+)/)[2];
    }

    ReplyDelete
  8. Thanks Nilesh,

    I am new to Javascript and I was looking for this. And found on your blog. Thanks again.

    ReplyDelete
  9. You should really update the original post. It's much better than having to read the comments.

    ReplyDelete
  10. But how to consider Black Lee's comment ?? Any help ?

    ReplyDelete