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
Get path and query string from URL using javascript
提问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.href
but 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.pathname
and location.search
:
使用location.pathname
和location.search
:
(location.pathname+location.search).substr(1)
回答by Miles Wilson
window.location.pathname + window.location.search
Will get you the base url /found-locations
plus the query string ?state=--&km=km
将为您提供基本网址/found-locations
和查询字符串?state=--&km=km
回答by Ivailo Karamanolev
回答by Hien Nguyen
If your url is a string, you can create URL
object and use pathname
and search
property.
如果您的 url 是字符串,则可以创建URL
对象并使用pathname
和search
属性。
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);