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

2019-02-16 04:19发布

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://"

3条回答
Explosion°爆炸
2楼-- · 2019-02-16 04:31

Use window.location.pathname.

查看更多
成全新的幸福
3楼-- · 2019-02-16 04:45
alert(window.location.pathname);

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

查看更多
走好不送
4楼-- · 2019-02-16 04:45

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"
查看更多
登录 后发表回答