tags:

views:

953

answers:

4

Hey,

I already have quite a bit of js on my site, so I want to have a function that grabs the domain name of the current url as efficiently as possible.

Example:

input : http://stackoverflow.com/questions/ask

result : stackoverflow.com

input : http://test.stackoverflow.com/questions/ask

result : test.stackoverflow.com

I guess the best way to start is with document.location, but I'm at odds what to do from there.

+13  A: 

Try document.location.hostname

RaYell
+2  A: 

link text

window.location.hostname and take away what is not needed as "www"

andres descalzo
+7  A: 

It depends on what you are going to use the domain name for and specifically whether or not you care about a specified port number. If you URL includes a port number like:

http://stackoverflow.com:80/question/ask

document.location.hostname will return "stackoverflow.com"

while, document.location.host will return "stackoverflow.com:80"

Which is better depends on your use case.

If you happen to be examining the domain name to know whether or not a script will be able to access a script/DOM in another frame/window, then note that the port number is significant. Browsers will not permit cross domain script access across frames/windows. For the purpose of comparing domain names, different port numbers can be considered different domains.

Mike Rustici
+1  A: 
var host=/([^\.]+\.)?([^\.]+)(\.[^\\/\\]+\/|\\)?/.exec(location.hostname) || [];
alert(host[2])
kennebec