【问题标题】:What's an easy way to get the url in the current window minus the domain name?在当前窗口中获取 url 减去域名的简单方法是什么?
【发布时间】:2023-04-03 23:41:01
【问题描述】:

我的 Javascript 不太热,所以在我开始一些混乱的字符串操作之前,我想我会问:

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

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

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

【问题讨论】:

    标签: javascript string url


    【解决方案1】:
    alert(window.location.pathname);
    

    Here's some documentation for you 为window.location。

    【讨论】:

    • 不清楚你是否想要它,但如果你可能想要包含 ?query 和 #fragment 部分(即域名后的 everything)然后添加 @987654326 @ 和 location.hash.
    • @bobince - +1 值得添加。谢谢。 :o)
    【解决方案2】:

    使用window.location.pathname。

    【讨论】:

      【解决方案3】:

      附加答案:

      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);
      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多