views:

58

answers:

2

I have a string like a=6&id=99 (i might store it in html as 'a=6&id=99' however thats not what js will see). I would like to convert that string into an object so i can do func(o.a); or o.id=44; How do i do that?

Part 2: How do i convert that object back to a query string? it would probably be trivial code that i can write.

+1  A: 
// convert string to object
str = 'a=6&id=99';
var arr = str.split('&');
var obj = {};
for(var i = 0; i < arr.length; i++) {
    var bits = arr[i].split('=');
    obj[bits[0]] = bits[1];
}
//alert(obj.a);
//alert(obj.id);

// convert object back to string
str = '';
for(key in obj) {
    str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1); 
alert(str);

​ ​ Try it here: http://jsfiddle.net/DUpQA/1/

karim79
+2  A: 

You can use jQuery.param.

Luc