Skip to content

Instantly share code, notes, and snippets.

@Bartunek
Created January 17, 2014 10:10
Show Gist options
  • Save Bartunek/8470960 to your computer and use it in GitHub Desktop.
Save Bartunek/8470960 to your computer and use it in GitHub Desktop.
Parsing and working with url parameters
// Function for parsing params from url (returning params in javascript object)
var parseUrlParams = function () {
var parReg = /[\?\&][a-zA-z0-9-~]+/g,
params = window.location.search.match(parReg),
result = {};
for (var i = params.length - 1; i >= 0; i--) {
params[i] = params[i].substring(1);
var valReg = new RegExp('[?&]'+params[i]+'=([^&#]*)'),
val = window.location.search.match(valReg) ? window.location.search.match(valReg)[1] : null;
result[params[i].replace('~', '_')] = val === 'true' ? true : val;
}
return result;
};
// Singleton creating object with property "params" and method getParam(paramName)
/*
* Usage:
* var urlParams = new UrlParams();
* urlParams.params // returning object with all url parameters
* urlParams.getParam(name) // method returning param value or false (if param doesn't exits)
*/
var UrlParams;
(function (){
var instance;
UrlParams = function UrlParams(){
if (instance) {
return instance;
}
instance = this;
this.params = {};
var parReg = /[\?\&][a-zA-z0-9-~]+/g,
params = window.location.search.match(parReg);
for (var i = params.length - 1; i >= 0; i--) {
params[i] = params[i].substring(1);
var valReg = new RegExp('[?&]'+params[i]+'=([^&#]*)'),
val = window.location.search.match(valReg) ? window.location.search.match(valReg)[1] : null;
this.params[params[i].replace('~', '_')] = val === 'true' ? true : val;
}
};
}());
UrlParams.prototype.getParam = function(param) {
return this.params[param] !== undefined ? this.params[param] : false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment