Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Usage:
* var q = new QueryParser();
*/
var QueryParser = function(option) {
var config = option || {};
var queriesMap = {};
var queryString = config.queryString !== undefined ? config.queryString : location.search;
return {
/**
* Get all the query params and their values
*/
getAll: function() {
var pairs = queryString.replace("?", "").split("&");
var allQueries = this.parseToObject(pairs, "=");
return allQueries;
},
/**
* A helper to parse an array into an object
*/
parseToObject: function(arrToParse) {
arrToParse.forEach(function(pair, i) {
var keyandval = pair.split("=");
queriesMap[keyandval[0]] = keyandval[1];
});
return queriesMap;
},
/**
A helper to parse an array into an object
Usage:
// For ueryString: "?foo=bar&baz=qux"
var q = new QueryParser();
q.getValueByParam("foo"); // returns "bar"
*/
getValueByParam: function(paramName) {
if (queriesMap[paramName] !== undefined) { return queriesMap[paramName]; }
var rgx = new RegExp(paramName + "=(.+)&");
return queryString.match(rgx)[1];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment