在 JavaScript 中解析查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2090551/
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
Parse query string in JavaScript
提问by sinaw
I need to parse the query string www.mysite.com/default.aspx?dest=aboutus.aspx.
How do I get the destvariable in JavaScript?
我需要解析查询字符串www.mysite.com/default.aspx?dest=aboutus.aspx。如何dest在 JavaScript 中获取变量?
回答by Tarik
Here is a fast and easy way of parsing query strings in JavaScript:
这是在 JavaScript 中解析查询字符串的一种快速简便的方法:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
现在向page.html?x=Hello发出请求:
console.log(getQueryVariable('x'));
回答by Raivo Fishmeister
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2into object {hello: 1, another: 2}. From there, it's easy to extract the variable you need.
将查询字符串 likehello=1&another=2转换为 object {hello: 1, another: 2}。从那里,很容易提取您需要的变量。
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3". To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
也就是说,它不处理诸如"hello=1&hello=2&hello=3". 要使用它,您必须在添加之前检查您创建的对象的属性是否存在,并将其值转换为数组,推送任何其他位。
回答by Salman von Abbas
You can also use the excellent URI.jslibrary by Rodney Rehm. Here's how:-
您还可以使用Rodney Rehm的优秀URI.js库。就是这样:-
var qs = URI('www.mysite.com/default.aspx?dest=aboutus.aspx').query(true); // == { dest : 'aboutus.aspx' }
alert(qs.dest); // == aboutus.aspx
And to parse the query string of current page:-
并解析当前页面的查询字符串:-
var $_GET = URI(document.URL).query(true); // ala PHP
alert($_GET['dest']); // == aboutus.aspx
回答by drzaus
Me too! http://jsfiddle.net/drzaus/8EE8k/
我也是!http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
(注意:没有花哨的嵌套或重复检查)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
和测试:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
结果是:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
回答by Henry Rusted
Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...
这是我的版本松散地基于上面 Braceyard 的版本,但解析为“字典”并支持不带“=”的搜索参数。在我的 JQuery $(document).ready() 函数中使用它。参数作为键/值对存储在 argsParsed 中,您可能希望将其保存在某处...
'use strict';
function parseQuery(search) {
var args = search.substring(1).split('&');
var argsParsed = {};
var i, arg, kvp, key, value;
for (i=0; i < args.length; i++) {
arg = args[i];
if (-1 === arg.indexOf('=')) {
argsParsed[decodeURIComponent(arg).trim()] = true;
}
else {
kvp = arg.split('=');
key = decodeURIComponent(kvp[0]).trim();
value = decodeURIComponent(kvp[1]).trim();
argsParsed[key] = value;
}
}
return argsParsed;
}
parseQuery(document.location.search);
回答by jsdw
Following on from my comment to the answer @bobby posted, here is the code I would use:
继我对@bobby 发布的答案的评论之后,这是我将使用的代码:
function parseQuery(str)
{
if(typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {}, first, second;
for(var i = 0; i < s_length; i++)
{
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if(first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if(typeof query[first] == "undefined") query[first] = second;
else if(query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This code takes in the querystring provided (as 'str') and returns an object. The string is split on all occurances of &, resulting in an array. the array is then travsersed and each item in it is split by "=". This results in sub arrays wherein the 0th element is the parameter and the 1st element is the value (or undefined if no = sign). These are mapped to object properties, so for example the string "hello=1&another=2&something" is turned into:
此代码接受提供的查询字符串(作为“str”)并返回一个对象。字符串在 & 的所有出现处被拆分,从而产生一个数组。然后遍历数组,其中的每个项目都被“=”分割。这导致子数组,其中第 0 个元素是参数,第 1 个元素是值(如果没有 = 符号,则未定义)。这些映射到对象属性,因此例如字符串“hello=1&another=2&something”被转换为:
{
hello: "1",
another: "2",
something: undefined
}
In addition, this code notices repeating reoccurances such as "hello=1&hello=2" and converts the result into an array, eg:
此外,这段代码会注意到重复出现,例如“hello=1&hello=2”,并将结果转换为数组,例如:
{
hello: ["1", "2"]
}
You'll also notice it deals with cases in whih the = sign is not used. It also ignores if there is an equal sign straight after an & symbol.
您还会注意到它处理不使用 = 符号的情况。它也会忽略 & 符号后面是否有等号。
A bit overkill for the original question, but a reusable solution if you ever need to work with querystrings in javascript :)
对于原始问题来说有点矫枉过正,但是如果您需要在 javascript 中使用查询字符串,这是一个可重用的解决方案:)
回答by CB01
If you know that you will only have that one querystring variable you can simply do:
如果您知道您将只有一个查询字符串变量,您可以简单地执行以下操作:
var dest = location.search.replace(/^.*?\=/, '');
回答by amiuhle
The following function will parse the search string with a regular expression, cache the result and return the value of the requested variable:
以下函数将使用正则表达式解析搜索字符串,缓存结果并返回请求变量的值:
window.getSearch = function(variable) {
var parsedSearch;
parsedSearch = window.parsedSearch || (function() {
var match, re, ret;
re = /\??(.*?)=([^\&]*)&?/gi;
ret = {};
while (match = re.exec(document.location.search)) {
ret[match[1]] = match[2];
}
return window.parsedSearch = ret;
})();
return parsedSearch[variable];
};
You can either call it once without any parameters and work with the window.parsedSearchobject, or call getSearchsubsequently.
I haven't fully tested this, the regular expression might still need some tweaking...
您可以在没有任何参数的情况下调用一次并使用该window.parsedSearch对象,也可以getSearch随后调用。我还没有完全测试过这个,正则表达式可能仍然需要一些调整......
回答by Madbreaks
How about this?
这个怎么样?
function getQueryVar(varName){
// Grab and unescape the query string - appending an '&' keeps the RegExp simple
// for the sake of this example.
var queryStr = unescape(window.location.search) + '&';
// Dynamic replacement RegExp
var regex = new RegExp('.*?[&\?]' + varName + '=(.*?)&.*');
// Apply RegExp to the query string
var val = queryStr.replace(regex, "");
// If the string is the same, we didn't find a match - return false
return val == queryStr ? false : val;
}
..then just call it with:
..然后只需调用它:
alert('Var "dest" = ' + getQueryVar('dest'));
Cheers
干杯
回答by jdavid.net
I wanted a simple function that took a URL as an input and returned a map of the query params. If I were to improve this function, I would support the standard for array data in the URL, and or nested variables.
我想要一个简单的函数,它将 URL 作为输入并返回查询参数的映射。如果我要改进此功能,我将支持 URL 中的数组数据和/或嵌套变量的标准。
This should work back and for with the jQuery.param( qparams ) function.
这应该适用于 jQuery.param( qparams ) 函数。
function getQueryParams(url){
var qparams = {},
parts = (url||'').split('?'),
qparts, qpart,
i=0;
if(parts.length <= 1 ){
return qparams;
}else{
qparts = parts[1].split('&');
for(i in qparts){
qpart = qparts[i].split('=');
qparams[decodeURIComponent(qpart[0])] =
decodeURIComponent(qpart[1] || '');
}
}
return qparams;
};

