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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16376438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:23:13  来源:igfitidea点击:

Get path and query string from URL using javascript

javascripturluri

提问by doniyor

I have this:

我有这个:

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

I want this:

我要这个:

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

how do i do this in javascript?

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

I tried window.location.hrefbut it is giving me whole url
I tried window.location.pathname.substr(1)but it is giving me found-locations/

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

回答by Gumbo

Use location.pathnameand location.search:

使用location.pathnamelocation.search

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

回答by Miles Wilson

window.location.pathname + window.location.search

Will get you the base url /found-locationsplus the query string ?state=--&km=km

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

回答by Ivailo Karamanolev

URI.jsis a nice JavaScript library for parsing URIs. It can do what you requested with a nice fluent syntax.

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

回答by Hien Nguyen

If your url is a string, you can create URLobject and use pathnameand searchproperty.

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