Javascript: get everything window.location except host?

I like

http://www.mydomain.com/hello/you

with top.location.host , I can get "http://www.mydomain.com"

with window.location.href I can get "http://www.mydomain.com/hello/you"

is there a chance to get only "/hello/you" ???

+6
javascript
source share
2 answers
 location.pathname 

pathname will return the path only. If you want a querystring and optionally hash , you will need to combine the search and hash properties. Consider this URL:

 http://www.example.com/path/to/glory?key=value&world=cup#part/of/page location.pathname => "/path/to/glory" location.search => "?key=value&world=cup" location.hash => "#part/of/page" 

If you want everything

 /path/to/glory?key=value&world=cup#part/of/page 

then just put it all together:

 location.pathname + location.search + location.hash 

Always wanted to use with somewhere. It looks like a great opportunity :)

 with(location) { pathname + search + hash; } 
+15
source share

Another approach would be to exclude the protocol and host from the whole href using a substring.

 window.location.href.substring( (window.location.protocol+'//'+window.location.host).length ) 

If your URL is http://google.com/test?whatever=1#hello , it will return /test?whatever=1#hello .

0
source share

All Articles