Javascript 在当前窗口中获取 url 减去域名的简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3955959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:51:17  来源:igfitidea点击:

What's an easy way to get the url in the current window minus the domain name?

javascriptstringurl

提问by Kenji Crosland

My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:

我的 Javascript 不是很热,所以在我进入一些混乱的字符串操作之前,我想我会问:

If the current url is: "http://stackoverflow.com/questions/ask"

如果当前 url 是:“http://stackoverflow.com/questions/ask”

What's a good way to to just get: "/questions/ask" ?

什么是获得: "/questions/ask" 的好方法?

Basically I want a string that matches the Url without the domain or the "http://"

基本上我想要一个与没有域或“http://”的 Url 匹配的字符串

回答by user113716

alert(window.location.pathname);

Here's some documentation for youfor window.location.

这里有一些文档供您使用window.location

回答by Bahadir Tasdemir

ADDITIONAL ANSWER:

附加答案:

window.location.pathname itself is just not enough because it doesn't include the query part, and also URN if exists:

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"

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:

这将正确获取以下 URL 部分:

http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"

回答by xmarcos

Use window.location.pathname.

使用window.location.pathname.