Skip to content

Instantly share code, notes, and snippets.

@grantjbutler
Forked from 140bytes/LICENSE.txt
Created May 23, 2011 16:51
Show Gist options
  • Save grantjbutler/987036 to your computer and use it in GitHub Desktop.
Save grantjbutler/987036 to your computer and use it in GitHub Desktop.
Query string parsing
function(
a, // the query string
b, // placeholder
c, // placeholder
d, // placeholder
e // placeholder
) {
for(
b = /[?&]?([^=]+)=([^&]*)/g, // Create the regular expression to match key-value pairs.
c = {}, // Create the object to store all the key-value pairs.
e = decodeURIComponent; // Alias the decodeURIComponent function to save bytes.
d = b.exec(a.replace(/\+/g, ' '));
c[e(d[1])] = e(d[2]) // store in the object.
);
return c; // return the object with the keys and pairs.
}
function(a,b,c,d,e){for(b=/[?&]?([^=]+)=([^&]*)/g,c={},e=decodeURIComponent;d=b.exec(a.replace(/\+/g,' '));c[e(d[1])]=e(d[2]));return c;}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Grant Butler
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "query_string",
"description": "Parses a query string and returns key-pairs as in object.",
"keywords": [
"query string",
"query",
"url"
]
}
function e(
a, // The name of the key that we want the value for.
b, // Placeholder
c // Placeholder
) {
if(e.a == []._) // Check if we e.a, where we store the object, exists.
for( // If not, we go into this for loop to create it.
b = /[?&]?([^=]+)=([^&]*)/g, // Setup the RegEx.
e.a = {}; // Initialize e.a.
c = b.exec(location.search); // Execute the RegEx.
e.a[c[1]]=c[2] // Assign the pair.
);
return e.a[a]; // Return the value for the provided key.
}
function e(a,b,c){if(e.a==[]._)for(b=/\??([^=]+)=([^&]+)&?/g,e.a={};c=b.exec(location.search);e.a[c[1]]=c[2]);return e.a[a];}
@atk
Copy link

atk commented Jun 29, 2011

You could put the [?&] inside the expression part for the parameter key: instead of /[?&]?([^=]+)=([^&]*)/g, you could use /([^=?&]+)=([^&]*)/g, since those characters are not allowed unencoded within those keys anyway.

@defims
Copy link

defims commented Jun 13, 2016

failed when test "?a=1&b=2#c"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment