Current URL without parameters, hash, http (s): //

I am looking for a neat way to get the url of the current document in Javascript.

  • URL must be clean of parameters (? Parameter1 = bla & parameter2 = bla)
  • URL must be hash-free (#jumppoint)
  • http / https should be deleted / merged into http

I know I can get the current URL with location.href and then use some regular expressions to clear it, but maybe there is a better / cleaner solution to get rid of garbage?

+24
source share
8 answers

There are many other options than href in window.location . See the full link here: https://developer.mozilla.org/en/DOM/window.location

What you are looking for as a starter could be window.location.hostname :

"host name (without port number or square Brackets)."

In the example URL http://[www.example.com]:80/search?q=devmo#test the host name will be www.example.com .

If you also want to include the path and force the http: // protocol, try:

 'http://' + window.location.hostname + window.location.pathname; 

As a side note, a great trick to get the same parameters from a different URL as window.location is to create an empty anchor:

 var a = document.createElement('a'); a.href = 'http://www.example.com:80/search?q=devmo#test'; console.log('http://' + a.hostname + a.pathname); 
+46
source

None of these answers relate to the fact that the protocol can be http or https, as in the OP header. For this, I suggest:

 document.location.protocol +"//"+ document.location.hostname + document.location.pathname 
+27
source

Location object got what you need

 window.location.hostname + window.location.pathname 
+5
source

You have a document.location object, so:

 var oLoc = document.location, sUrl = oLoc.protocol + oLoc.hostname; // or "http://" + oLoc.hostname 
+2
source

You can use these replace functions to remove hash and search arguments and normalize https to http:

 url = url.replace(/#[^#]*$/, "").replace(/\?[^\?]*$/, "").replace(/^https:/, "http:"); 

Or, if all you really need is a domain and a path, you can simply use this:

 window.location.hostname + window.location.pathname 
+2
source

Try this snippet:

 if (!window.location.origin){ // For IE window.location.origin = window.location.protocol + "//" + (window.location.port ? ':' + window.location.port : ''); } url = window.location.origin + window.location.pathname; document.write('Origin url: ' + url); 
+2
source

This page shows that you can probably use window.location.host to get the part you are interested in. I have not tested it, however.

0
source

Try:

 window.location.hostname;
window.location.hostname; 
0
source

Source: https://habr.com/ru/post/944436/


All Articles