Skip to content

Instantly share code, notes, and snippets.

@gists-app-test
Forked from nessthehero/qs.js
Created September 12, 2012 14:31
Show Gist options
  • Save gists-app-test/3706987 to your computer and use it in GitHub Desktop.
Save gists-app-test/3706987 to your computer and use it in GitHub Desktop.
Get the query string(s)

Usage

// index.html?keywords=test

qs(); // { name: 'keywords', values: [ 'test' ] }

But wait, why store the value in an array?

Because of

// index.html?category=4&category=5&category=6

qs(); // { name: 'category', values: [ '4', '5', '6' ] }

which is a perfectly valid use of query strings.

Also

qs('category'); // [ '4', '5', '6' ] 
function qs() {
var vars = [],
grabUrl = window.location.search,
parts,
pieces,
qs = '',
qsVals = [];
if (typeof arguments[0] == 'string') {
qs = arguments[0];
}
if (typeof grabUrl != 'undefined') {
grabUrl = grabUrl.replace("?", '');
parts = grabUrl.split("&");
for (var j in parts) {
pieces = parts[j].split('=');
if (vars.length != 0) {
for (var i in vars) {
if (vars[i].name == pieces[0].toString()) {
vars[i].values.push(pieces[1]);
} else {
vars.push({ "name" : pieces[0].toString(), "values" : [pieces[1]] });
}
}
} else {
vars.push({ "name" : pieces[0].toString(), "values" : [pieces[1]] });
}
}
if (qs != '') {
for (var i in vars) {
if (vars[i].name == qs) {
return vars[i].values;
}
}
}
return vars;
} else {
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment