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


70

我有这个:

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/


Answers:



47
window.location.pathname + window.location.search

将为您提供基本网址/found-locations以及查询字符串?state=--&km=km



5

如果您的网址是字符串,则可以创建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);



1

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.