Javascript:获取window.location除了主机之外的所有内容?
我喜欢 使用Javascript:获取window.location除了主机之外的所有内容?,javascript,Javascript,我喜欢 使用top.location.host,我可以获得“http://www.mydomain.com“ 使用window.location.href我可以获得”http://www.mydomain.com/hello/you“ 是否有机会只获得“/hello/you” location.pathname pathname将只返回路径。如果需要查询字符串和可选的散列,则还需要将搜索和散列属性组合起来。考虑这个URL: http://www.example.com/path/to/glo
top.location.host
,我可以获得“http://www.mydomain.com“
使用window.location.href
我可以获得”http://www.mydomain.com/hello/you“
是否有机会只获得“/hello/you”
location.pathname
pathname
将只返回路径。如果需要查询字符串
和可选的散列
,则还需要将搜索
和散列
属性组合起来。考虑这个URL:
http://www.example.com/path/to/glory?key=value&world=cup#part/of/page
location.pathname => "/path/to/glory"
location.search => "?key=value&world=cup"
location.hash => "#part/of/page"
如果你想要整件事
/path/to/glory?key=value&world=cup#part/of/page
然后将所有这些连接起来:
location.pathname + location.search + location.hash
总是想在某个地方使用。这看起来是个绝佳的机会:)
另一种方法是使用子字符串将协议和主机从整个href中排除
window.location.href.substring(
(window.location.protocol+'//'+window.location.host).length
)
如果您的url是http://google.com/test?whatever=1#hello
它将返回/test?whatever=1#你好
这可能与jQuery有什么关系?Anurag:在编辑时,您最好去掉多余的toString
调用location.host
.yikes@no,你更改时我覆盖了吗?Anurag,不,我还不能编辑:)别忘了search
和hash
@Matthew-OP的问题中没有列出查询字符串或哈希,所以我不能假设他会想要它,但我能做的是详细说明我的答案:)
window.location.href.substring(
(window.location.protocol+'//'+window.location.host).length
)