Last active
August 29, 2015 14:27
-
-
Save markx/44128f8d5c7069bd3621 to your computer and use it in GitHub Desktop.
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 into an object. | |
* | |
* @method queryStringToObject | |
* @param {String} str Query string. Use the query string from URL if this parameter is not provided. | |
* @return {Object} Returns the object created from query string | |
*/ | |
queryStringToObject: function (str) { | |
var i, pair; | |
var result = {}; | |
var params = []; | |
str = str|| document.location.search; | |
str = str.replace(/(^\?)/,''); //remove '?' at the start | |
params = str.split("&"); | |
for(i=0; i<params.length; i++) { | |
pair = params[i].split('='); | |
result[pair[0]] = pair[1]; | |
} | |
return result; | |
}, | |
objectToQueryString: function (obj) { | |
var params=[]; | |
for (var k in obj) { | |
if (obj.hasOwnProperty(k)) { | |
params.push(k+'='+obj[k]); | |
} | |
} | |
return params.join('&'); | |
} | |
---------------------------------------------------------------------------------- | |
describe.only("queryStringToObject() function", function() { | |
it("should parse the string and return an object", function() { | |
var querystring = '?a=1&b=2'; | |
var obj = VHS.util.queryStringToObject(querystring); | |
expect(obj.a).to.equal('1'); | |
expect(obj.b).to.equal('2'); | |
}); | |
it("should get queryString from URL if not provided as an argument", function() { | |
var seachBackup = window.location.search; | |
window.location.search = '?a=1&b=2'; | |
console.log(window.location.search); | |
var obj = VHS.util.queryStringToObject(); | |
expect(obj.a).to.equal('1'); | |
expect(obj.b).to.equal('2'); | |
window.location.search = seachBackup; | |
}); | |
}); | |
describe("objectToQueryString() function", function() { | |
it("should iterate through the object and return corresponding string", function() { | |
var obj = { | |
a: 1, | |
b: 2 | |
} | |
var str = VHS.util.objectToQueryString(obj); | |
expect(str).to.satisfy(function(str) { return str === 'b=2&a=1' || str === 'a=1&b=2'}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment