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

前端 未结 3 2043
离开以前
离开以前 2020-12-29 17:50

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

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

相关标签:
3条回答
  • 2020-12-29 18:45

    Use window.location.pathname.

    0 讨论(0)
  • 2020-12-29 18:47
    alert(window.location.pathname);
    

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

    0 讨论(0)
  • 2020-12-29 18:49

    ADDITIONAL ANSWER:

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

    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:

    http://some.domain/path-value?query=string#testURN
    alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
    
    0 讨论(0)
提交回复
热议问题