Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to grab domain/host name using javascript

Tags:

javascript

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 : https://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.

like image 844
stan Avatar asked Aug 05 '09 18:08

stan


People also ask

How can we get hostname and port information in JavaScript?

If you only want to return the hostname value (excluding the port number), use the window. location. hostname method instead. This will return a string value containing the hostname and, if the port value is non-empty, a : symbol along with the port number of the URL.

How do I get the current domain in HTML?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.

How do I find the domain of a string?

Firstly, we'd need to extract the host from the given URL value. We can use the URI class: String urlString = "https://www.baeldung.com/java-tutorial"; URI uri = new URI(urlString); String host = uri. getHost();


2 Answers

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.

like image 72
Mike Rustici Avatar answered Sep 21 '22 04:09

Mike Rustici


Try document.location.hostname

like image 28
RaYell Avatar answered Sep 19 '22 04:09

RaYell