Skip to content

Instantly share code, notes, and snippets.

@juanmanuelramallo
Last active July 5, 2017 19:21
Show Gist options
  • Save juanmanuelramallo/27c8dc9cf3866e627993dce2b500dabe to your computer and use it in GitHub Desktop.
Save juanmanuelramallo/27c8dc9cf3866e627993dce2b500dabe to your computer and use it in GitHub Desktop.
Handling URL Parameters with plain javascript and Lodash
function URLParameters(str) {
this.queryString = typeof(str) === 'undefined' ? document.location.search : str;
this.params = {};
this.parse = function(string) {
if (string && !_.isEmpty(string)) {
var obj = {};
var pairs = string.replace('?', '').split('&');
pairs = _.map(pairs, function(pair, index) {
return pair.split('=');
});
_.forEach(pairs, function(pair, index) {
obj[pair[0]] = obj[pair[0]] || [];
obj[pair[0]].push(pair[1]);
});
return obj;
} else {
return {};
}
}
this.toString = function() {
if (this.isEmpty()) {
return '';
} else {
var str = _.map(this.params, function(values, key) {
return _.map(values, function(value) {
return key + '=' + value;
}).join('&');
}).join('&');
return ('?' + str);
}
}
this.get = function(key) {
return this.params[key];
}
this.set = function(key, value) {
return this.params[key] = [value];
}
this.append = function(key, value) {
this.params[key] = this.params[key] || [];
return this.params[key].push(value);
}
this.delete = function(key) {
return delete this.params[key];
}
this.deleteAll = function() {
return this.params = {}
}
this.isEmpty = function() {
return _.isEmpty(this.params);
}
this.params = this.parse(this.queryString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment