get domain name from url

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sreemathy2000
    New Member
    • Oct 2007
    • 40

    get domain name from url

    i need to get the domain name from the url in javascript.

    for eg if the url is "http://bytes.com/forum/newthread.php", i need to get bytes.com alone.

    any quick help will be appreciated.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5388

    #2
    you may use:

    [CODE=javascript]var hn = window.location .hostname;[/CODE]

    Comment

    • sreemathy2000
      New Member
      • Oct 2007
      • 40

      #3
      Thanks for the quick reply....this returns the domain name of the current url...
      i need this to be a utility function where i can pass a url and get the domain name.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5388

        #4
        hmmm ... that's another question ... try a regExp like the following:

        [CODE=javascript]var url = 'http://bytes.com/forum/newthread.php';

        function get_hostname_fr om_url(url) {
        return url.match(/:\/\/(.[^/]+)/)[1];
        }

        alert(get_hostn ame_from_url(ur l));[/CODE]
        kind regards

        Comment

        • sreemathy2000
          New Member
          • Oct 2007
          • 40

          #5
          k..thanks..i'll try that

          Comment

          • rnd me
            Recognized Expert Contributor
            • Jun 2007
            • 427

            #6
            looks a little fragile.

            try url.split(/\/+/g)[1];

            Comment

            Working...