Connecting Tech Pros Worldwide Forums | Help | Site Map

get domain name from url

Member
 
Join Date: Oct 2007
Posts: 39
#1: Sep 4 '08
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's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,134
#2: Sep 4 '08

re: get domain name from url


you may use:

Expand|Select|Wrap|Line Numbers
  1. var hn = window.location.hostname;
Member
 
Join Date: Oct 2007
Posts: 39
#3: Sep 4 '08

re: get domain name from url


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.
gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,134
#4: Sep 4 '08

re: get domain name from url


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

Expand|Select|Wrap|Line Numbers
  1. var url = 'http://bytes.com/forum/newthread.php';
  2.  
  3. function get_hostname_from_url(url) {
  4.     return url.match(/:\/\/(.[^/]+)/)[1];
  5. }
  6.  
  7. alert(get_hostname_from_url(url));
kind regards
Member
 
Join Date: Oct 2007
Posts: 39
#5: Sep 5 '08

re: get domain name from url


k..thanks..i'll try that
rnd me's Avatar
Expert
 
Join Date: Jun 2007
Location: Urbana IL
Posts: 411
#6: Sep 8 '08

re: get domain name from url


looks a little fragile.

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