Javascript 什么';获取当前窗口中的url减去域名的简单方法是什么?
我的Javascript不是很热,所以在我开始一些混乱的字符串操作之前,我想我应该问: 如果当前url为:http://stackoverflow.com/questions/ask" 什么是一个好的方式来获得:“/问题/提问” 基本上,我想要一个与Url匹配的字符串,而不需要域或“http://”Javascript 什么';获取当前窗口中的url减去域名的简单方法是什么?,javascript,string,url,Javascript,String,Url,我的Javascript不是很热,所以在我开始一些混乱的字符串操作之前,我想我应该问: 如果当前url为:http://stackoverflow.com/questions/ask" 什么是一个好的方式来获得:“/问题/提问” 基本上,我想要一个与Url匹配的字符串,而不需要域或“http://” 对于window.location使用window.location.pathname其他答案: window.location.pathname本身还不够,因为它不包括查询部分,如果存在,还包括U
对于
window.location
使用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, "")
这将正确获取以下URL部分:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
现在还不清楚您是否想要它,但如果您可能想要
?查询和片段包含的部分(即域名后面的所有内容),然后添加位置。搜索和位置。散列@bobince-+1个值得添加的内容。谢谢o) 这应该是公认的答案,因为无论将来添加查询字符串还是散列,它都更具未来感。很好的解决方案。或者更简单的语法:window.location.href.substring(window.location.origin.length)代码>
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"