Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: get window.location everything but host?

Tags:

javascript

i have 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 just "/hello/you" ???

like image 225
matt Avatar asked Jul 16 '10 01:07

matt


People also ask

Can I use window location hostname?

window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page. window.location.protocol returns the web protocol used (http: or https:) window.location.assign() loads a new document.

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.

Does window location host include port?

host: This property also returns the same hostname but it also includes the port number. In case, if the port number is not available, then it will just return the hostname.


2 Answers

location.pathname

pathname will only return the path. If you want the querystring and optionally hash, you would need to combine the search and hash properties as well. 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 the entire thing,

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

then just concatenate all these:

location.pathname + location.search + location.hash

Always wanted to use with somewhere. This looks like the perfect opportunity :)

with(location) {
    pathname + search + hash;
}
like image 134
Anurag Avatar answered Sep 26 '22 08:09

Anurag


Another approach would be excluding the protocol and host from the entire href using 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.

like image 34
Alex K Avatar answered Sep 22 '22 08:09

Alex K