What's an easy way to get the url in the curre

2019-02-16 03:47发布

问题:

My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:

If the current url is: "http://stackoverflow.com/questions/ask"

What's a good way to to just get: "/questions/ask" ?

Basically I want a string that matches the Url without the domain or the "http://"

回答1:

alert(window.location.pathname);

Here's some documentation for you for window.location.



回答2:

ADDITIONAL ANSWER:

window.location.pathname itself is just not enough because it doesn't include the query part, and also URN if exists:

Sample URI                      = "http://some.domain/path-value?query=string#testURN"
window.location.pathname result = "/path-value"
window.location.search result   = "?query=string"
pathname + search result        = "/path-value?query=string"

If you want to get all the values just except the domain name, you can use the following code:

window.location.href.replace(window.location.origin, "")

This gets the following URL parts correctly:

http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"


回答3:

Use window.location.pathname.