Skip to content

Instantly share code, notes, and snippets.

@antonioaguilar
Forked from ryoppy/getQueryParams.js
Created January 9, 2016 18:02
Show Gist options
  • Save antonioaguilar/808748cee9c575ed89f7 to your computer and use it in GitHub Desktop.
Save antonioaguilar/808748cee9c575ed89f7 to your computer and use it in GitHub Desktop.
Parse query string. use Underscore.js.
/**
* Parse query string.
* ?a=b&c=d to {a: b, c: d}
* @param {String} (option) queryString
* @return {Object} query params
*/
getQueryParams: function(queryString) {
var query = (queryString || window.location.search).substring(1); // delete ?
if (!query) {
return false;
}
return _
.chain(query.split('&'))
.map(function(params) {
var p = params.split('=');
return [p[0], decodeURIComponent(p[1])];
})
.object()
.value();
}
// --- Jasmine test
describe('_.getQueryParams', function() {
it('?a=1', function() {
var result = _.getQueryParams('?a=1');
expect(result).toEqual({a: '1'});
});
it('?a=1&b=2', function() {
var result = _.getQueryParams('?a=1&b=2');
expect(result).toEqual({a: '1', b: '2'});
});
it('?a=1&jp=ほげ&en=Hoge', function() {
var result = _.getQueryParams('?a=1&jp=%E3%81%BB%E3%81%92&en=Hoge');
expect(result).toEqual({a: '1', jp: 'ほげ', en: 'Hoge'});
});
it('?a=1&jp=%E3%81%BB%E3%81%92&en=Hoge', function() {
var result = _.getQueryParams('?a=1&jp=ほげ&en=Hoge');
expect(result).toEqual({a: '1', jp: 'ほげ', en: 'Hoge'});
});
it('?a&b=2', function() {
var result = _.getQueryParams('?a&b=2');
expect(result).toEqual({a: 'undefined', b: '2'});
});
it('', function() {
var result = _.getQueryParams('');
expect(result).toEqual(false);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment