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

don*_*yor 59 javascript url uri

我有这个:

http://127.0.0.1:8000/found-locations/?state=--&km=km
Run Code Online (Sandbox Code Playgroud)

我要这个:

found-locations/?state=--&km=km
Run Code Online (Sandbox Code Playgroud)

我如何在JavaScript中执行此操作?

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

Gum*_*mbo 91

使用location.pathnamelocation.search:

(location.pathname+location.search).substr(1)
Run Code Online (Sandbox Code Playgroud)

  • `.substr(1)` 是做什么用的? (2认同)
  • @AmitTripathi`.substr(1)`是在开始时删除斜杠 (2认同)

小智 41

window.location.pathname + window.location.search
Run Code Online (Sandbox Code Playgroud)

会得到你的基本网址/found-locations和查询字符串?state=--&km=km


Hie*_*yen 7

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

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

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


Iva*_*lev 5

URI.js是一个很好的JavaScript库,用于解析URI.它可以用流利的语法做你所要求的.


Ice*_*erg 5

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