Skip to content

Instantly share code, notes, and snippets.

@davidbiehl
Created May 23, 2014 22:06
Show Gist options
  • Save davidbiehl/95ee61cd8febf3a682aa to your computer and use it in GitHub Desktop.
Save davidbiehl/95ee61cd8febf3a682aa to your computer and use it in GitHub Desktop.
Query string to Object conversion in JavaScript
define([], function() {
/*
Public: Returns the query string decoded as an Object
queryArg - a String that is a query string. eg: "one=1&two=2&three"
Returns an Object
*/
return function(queryArg) {
var query = queryArg || window.location.search.substring(1);
var vars = query.split('&');
var retval = {};
for(var i = 0; i < vars.length; i++) {
var arg = vars[i];
if(arg.indexOf('=') == -1) {
retval[decodeURIComponent(arg)] = true;
} else {
var pair = arg.split('=')
retval[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
return retval;
}
})
define(function() {
QUnit.start();
/*
======== A Handy Little QUnit Reference ========
http://api.qunitjs.com/
Test methods:
module(name, {[setup][ ,teardown]})
test(name, callback)
expect(numberOfAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
throws(block, [expected], [message])
*/
/* require your app components
* for example, if you have /app/modules/doSomething.js, you can
* require(['modules/doSomething'], function(theModule) {
* // test the things
* });
*/
require(["lib/queryString"], function(queryString) {
module("queryString");
test('returns an object that represents the query string', function() {
deepEqual(queryString("one=1&two=2&three"), {one: "1", two: "2", three: true});
});
test("it uses the window.location.search.substring(1) by default", function() {
var customWindow = {
location: {
search: "?one=1&two=2&three"
}
};
(function(window) {
deepEqual(queryString(), {one: "1", two: "2", three: true});
})(customWindow);
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment