Created
January 17, 2014 10:10
-
-
Save Bartunek/8470960 to your computer and use it in GitHub Desktop.
Parsing and working with url parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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