-
-
Save appsparkler/e108910427810eb5dfcfe8ffc3288a28 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); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment