Parsing your querystrings with plain-old javascript has never been easier! For the developer that wants to code every line, or perhaps needs every drop of power/speed their browser can muster, VanillaJS is the winner. So here is a VanillaJS version of my querystring parser that does not require jQuery to run.
What is VanillaJS
VanillaJS is a loving name given to plain-old javascript, that’s right, the same javascript that you know and love is VanillaJS!
Code
/*
* querystring.js - v1.0.0
* Querystring utility in Javascript
* https://github.com/EldonMcGuinness/querystring.js
*
* Made by Eldon McGuinness
* Under MIT License
*
* Parameters:
* str - A string that you want the script to treat as the querystring
* instead of the actual page's querystring.
*/
queryString = function(str) {
var qso = {};
var qs = (str || document.location.search);
// Check for an empty querystring
if (qs == ""){
return qso;
}
// Normalize the querystring
qs = qs.replace(/(^\?)/,'')
.replace(/;/g,'&');
while (qs.indexOf("&&") != -1){
qs = qs.replace(/&&/g,'&');
}
qs = qs.replace(/([\&]+$)/,'');
// Break the querystring into parts
qs = qs.split("&");
// Build the querystring object
for (var i=0; i < qs.length; i++){
var qi = qs[i].split("=");
qi = map(qi, function (n) {return decodeURIComponent(n)});
if (qso[qi[0]] != undefined){
// If a key already exists then make this an object
if (typeof(qso[qi[0]]) == "string"){
var temp = qso[qi[0]];
if (qi[1] == ""){
qi[1] = null;
}
//console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]");
qso[qi[0]] = [];
qso[qi[0]].push(temp);
qso[qi[0]].push(qi[1]);
}else if (typeof(qso[qi[0]]) == "object"){
if (qi[1] == ""){
qi[1] = null;
}
//console.log("Duplicate key: ["+qi[0]+"]["+qi[1]+"]");
qso[qi[0]].push(qi[1]);
}
}else{
// If no key exists just set it as a string
if (qi[1] == ""){
qi[1] = null;
}
//console.log("New key: ["+qi[0]+"]["+qi[1]+"]");
qso[qi[0]] = qi[1];
}
}
function map(arr, func){
for (var i=0; i<arr.length; i++ ){
arr[i] = func(arr[i]);
}
return arr;
}
return qso;
}
Usage
To get the results of the querystring you simply need to invoke the plugin. additionally, you can refer directly to the part of the object that you want.
//To copy the entire querystring object into a variable
var queryString = querystring();
//To get only the field named "q"
var query = querystring()["q"];
//Remember, if there is more than one item with the same name, you will get an
//array that contains the responses.
//Example URL: /page.html?q=something&q=somethingelse
var query = querystring()["q"];
//query[0] yields the string "something"
//query[1] yields the string "somethingelse"
Useful Right!?
If you find this or any of my other contributions useful consider sharing them on social media.
Corrections or Changes
If you think something is not right or should be changed, feel free to comment or submit fixes on Github.