Last active
March 28, 2019 17:31
-
-
Save ryoppy/5780748 to your computer and use it in GitHub Desktop.
Parse query string. use Underscore.js.
This file contains hidden or 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
/** | |
* 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); | |
}); | |
}); |
Nice one!
10x!
10x:fried_shrimp:!
Nice One! Thanks.
I would add in Underscore Mixin
/Mixin within Underscore
_.mixin({
QueryParams: _QueryParams
});
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();
ty. helped a lot
Thanks, used it with lodash, just replacing .object()
with .fromPairs()
nice....Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!!