如何在Javascript中解析URL查询参数? [英] How do I parse a URL query parameters, in Javascript?
问题描述
可能重复:
如何在JavaScript中获取查询字符串值?
在Javascript中,如何获取URL字符串的参数(而不是当前的URL)?
In Javascript, how can I get the parameters of a URL string (not the current URL)?
喜欢:
www.domain.com/?v=123&p=hello
我可以在JSON对象中获得v和p吗?
Can I get "v" and "p" in a JSON object?
推荐答案
今天(这个答案后2。5年)你可以安全使用 数组.forEach
。正如@ricosrealm建议的那样,在这个函数中使用了 decodeURIComponent
。
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
实际上并不是那么简单,请看同行 - 评论中的评论,尤其是:
actually it's not that simple, see the peer-review in the comments, especially:
- 基于散列的路由(@cmfolio)
- 数组参数(@ user2368055)
- 正确使用decodeURIComponent(@AndrewF)
也许这应该去到codereview SE,但这里是更安全和无正则表达式的代码:
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
我还替换了非编码 +
根据这篇文章的空间这也是指导如何编码遵守RFC 3986的有用指南。
I also replaced non-encoded +
for space according to this article which is also useful guide how to encode adhering to RFC 3986.
注意结果[key] [index] = val
:创建一个新的数组项,它是可枚举的,因此它可以通过 forEach
调用进行迭代。因此,您甚至可以解析网址,例如
Note the result[key][index] = val
: a new array item is created, it is enumerable, so it can be iterated by forEach
call. Therefore, you can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
这篇关于如何在Javascript中解析URL查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!