【问题标题】:Get path and query string from URL using javascript使用 javascript 从 URL 获取路径和查询字符串
【发布时间】:2013-04-28 21:24:02
【问题描述】:

我有这个:

http://127.0.0.1:8000/found-locations/?state=--&km=km

我想要这个:

found-locations/?state=--&km=km

我如何在 javascript 中做到这一点?

我试过window.location.href,但它给了我整个网址
我试过window.location.pathname.substr(1),但它给了我found-locations/

【问题讨论】:

标签: javascript url uri


【解决方案1】:

使用location.pathnamelocation.search

(location.pathname+location.search).substr(1)

【讨论】:

【解决方案2】:
window.location.pathname + window.location.search

将为您提供基本 url /found-locations 加上查询字符串 ?state=--&km=km

【讨论】:

    【解决方案3】:

    如果您的 url 是一个字符串,您可以创建 URL 对象并使用 pathnamesearch 属性。

     let strurl = 'http://www.test.com/param1/param2?test=abc';
     let url = new URL(strurl)
     let pathandQuery = url.pathname + url.search;
    

    let strurl = 'http://www.test.com/param1/param2?test=abc';
    let url = new URL(strurl)
    let pathandQuery = url.pathname + url.search;
    
    console.log(pathandQuery);

    【讨论】:

    【解决方案4】:

    获取所有路径、查询甚至哈希:location.href.replace(location.origin, '')

    【讨论】:

      【解决方案5】:

      URI.js 是一个很好的用于解析 URI 的 JavaScript 库。它可以通过流畅的语法完成您的要求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-09
        • 2015-04-14
        • 1970-01-01
        • 2022-11-21
        • 2017-07-20
        相关资源
        最近更新 更多