I'm looking for a neat way of getting the URL of the current document in Javascript.
- The URL should be clean of parameters (?parameter1=bla¶meter2=bla)
- The URL should be clean of hash tags (#jumppoint)
- http/https should be removed/consolidated into http
I know i can get the current URL with location.href and then use some regular expressions to clean it up but maybe there is a nicer/cleaner solution for getting rid of the junk?
None of the given answers address the fact that the protocol can be http or https as in the OPs title. To accommodate this I suggest:
You have
document.location
object, so:You can use these replacement functions to remove the hash and search arguments and normalize https to http:
Or, if all you really want is the domain and path, you can just use this:
The Location object got what you need
There are many other parameters than the
href
inwindow.location
. See full reference here: https://developer.mozilla.org/en/DOM/window.locationWhat you are looking for as a starter might be the
window.location.hostname
:From the example URL
http://[www.example.com]:80/search?q=devmo#test
the hostname will bewww.example.com
.If you also want to include the path and force a http:// protocol, try:
As a side note, a nifty trick to get the same parameters from another URL than the window.location is to create an empty anchor:
Please try this snippet: