Hope you will find following function useful for converting query string into json object
var queryStringToJSON = function (url) {
if (url === '')
return '';
var pairs = (url || location.search).slice(1).split('&');
var result = {};
for (var idx in pairs) {
var pair = pairs[idx].split('=');
if (!!pair[0])
result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
}
return result;
}
Usage:
To get current windows query string
var result = queryStringToJSON() // without any parameter
To get json from custom query string:
var result = queryStringToJSON('?name=prem&age=30&HEIGHT=5.8')
output: {name:"prem", age:"30", height:"5.8"} //All keys are converted into small letters
To convert it back to url you can use jQuery param method
$.param(result)
To manipulate your query string you can simple use standard object manipulation in JavaScript and use $.param method again
result.age=35;
delete result['name'];
Working, but if you used url || location.search
then you should remove if(url === '') return ''
or it should be like,
var queryStringToJSON = function (url) {
url = url || location.search;// url or location.search
if (url === '')
return '';// return if url and location.search not found
// your remainig code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With