Skip to content

Instantly share code, notes, and snippets.

@ryoppy
Last active March 28, 2019 17:31
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ryoppy/5780748 to your computer and use it in GitHub Desktop.
Save ryoppy/5780748 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);
});
});
@builtbylane
Copy link

10x:fried_shrimp:!

@jadiagaurang
Copy link

Nice One! Thanks.

I would add in Underscore Mixin

/Mixin within Underscore
_.mixin({
    QueryParams: _QueryParams
});

@image72
Copy link

image72 commented Nov 28, 2015

var qsObj = _.chain(location.search ? location.search.slice(1).split('&') : '')
                .map(function(item) {
                  var p = item.split('=');

                  return [p[0], decodeURI(p[1])];
                })
                .object()
                .omit(_.isEmpty)
                .toJSON();

@pubkey
Copy link

pubkey commented Jan 30, 2016

ty. helped a lot

@kino90
Copy link

kino90 commented May 10, 2016

Thanks, used it with lodash, just replacing .object() with .fromPairs()

@appsparkler
Copy link

appsparkler commented Mar 7, 2017

nice....Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment