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.
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.
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.
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();
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.
Try document.location.hostname
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With