使用javascript从URL获取路径和查询字符串

Get path and query string from URL using javascript

本文关键字:查询 字符串 路径 获取 javascript URL 使用      更新时间:2023-09-26

我有这个:

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

我想要这个:

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

如何在javascript中做到这一点?

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

使用location.pathnamelocation.search:

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

将获得基本url /found-locations加上查询字符串?state=--&km=km

如果您的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);

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

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