Ken*_*and 40 javascript string url
我的Javascript不是那么热,所以在我进入一些凌乱的字符串操作之前,我想我会问:
如果当前网址是:"http://stackoverflow.com/questions/ask"
什么是获得的好方法:"/ questions/ask"?
基本上我想要一个与没有域或"http://"的Url匹配的字符串
use*_*716 68
alert(window.location.pathname);
Run Code Online (Sandbox Code Playgroud)
下面是一些对你的文档的window.location.
Bah*_*mir 24
其他答案:
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"
Run Code Online (Sandbox Code Playgroud)
如果要获取除域名之外的所有值,可以使用以下代码:
window.location.href.replace(window.location.origin, "")
Run Code Online (Sandbox Code Playgroud)
这会正确获取以下URL部分:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
Run Code Online (Sandbox Code Playgroud)