Skip to content

Instantly share code, notes, and snippets.

@nessthehero
Last active October 10, 2015 14:47
Show Gist options
  • Save nessthehero/3706727 to your computer and use it in GitHub Desktop.
Save nessthehero/3706727 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' ] 
BREI.data = {};
BREI.data.query = {};
BREI.util = {};
BREI.util.q = function() {
var vars = [],
grabUrl = window.location.search,
parts,
pieces,
qs = '',
qsVals = [];
if (typeof arguments[0] == 'string') {
qs = arguments[0];
}
if (typeof grabUrl != 'undefined' && grabUrl != '') {
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 ['-1'];
}
return vars;
} else {
return [];
}
}
BREI.util.qS = function(data) {
// returns ?blah=blah based on data you give it. Must be a JSON formatted object
//
// [
// {
// 'name': 'blah',
// 'values' : ['blah']
// }
// ]
var keys = [];
if (data.length != 0) {
for (var i in data) {
for (var j in data[i].values) {
keys.push(data[i].name + '=' + data[i].values[j]);
}
}
if (keys.length != 0) {
return '?' + keys.join('&');
} else {
return '';
}
} else {
return '';
}
}
BREI.util.qM = function(key, value) {
// Modifies an existing item in the BREI.data.query without clearing and resetting the entire object
// If not found, adds it
var val,
found = false;
if (typeof value != 'object') {
val = [value];
} else {
val = value;
}
for (var i in BREI.data.query) {
if (BREI.data.query[i].name == key) {
BREI.data.query[i].values = [];
for (var j in val) {
BREI.data.query[i].values.push(val[j]);
}
found = true;
}
}
if (!found) {
BREI.data.query.push({
'name':key,
'values': val
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment