【发布时间】:2023-04-03 23:41:01
【问题描述】:
我的 Javascript 不太热,所以在我开始一些混乱的字符串操作之前,我想我会问:
如果当前网址是:“http://stackoverflow.com/questions/ask”
什么是获得:“/questions/ask”的好方法?
基本上我想要一个与没有域或“http://”的 Url 匹配的字符串
【问题讨论】:
标签: javascript string url
我的 Javascript 不太热,所以在我开始一些混乱的字符串操作之前,我想我会问:
如果当前网址是:“http://stackoverflow.com/questions/ask”
什么是获得:“/questions/ask”的好方法?
基本上我想要一个与没有域或“http://”的 Url 匹配的字符串
【问题讨论】:
标签: javascript string url
alert(window.location.pathname);
Here's some documentation for you 为window.location。
【讨论】:
?query 和 #fragment 部分(即域名后的 everything)然后添加 @987654326 @ 和 location.hash.
使用window.location.pathname。
【讨论】:
附加答案:
window.location.pathname 本身是不够的,因为它不包括查询部分,如果存在,还包括 URN:
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"
如果要获取除域名以外的所有值,可以使用以下代码:
window.location.href.replace(window.location.origin, "")
或者按照@Maickel 的建议,使用更简单的语法:
window.location.href.substring(window.location.origin.length);
这会正确获取以下 URL 部分:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
【讨论】:
window.location.href.substring(window.location.origin.length);