Hillel Garcia Hillel Garcia - 3 months ago 11
Javascript Question

From string to an Object with Javascript

How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.

I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:

var numbers = "{one=1,two=2}"; //This is how I receive the string

numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies

document.write(numbers.one); //prints undefined


So this is your string

var str = '{one=1,two=2}';

replace = to : and also make this like json object or Key value pair(key should be always between quotes)

var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');

Now parse your string to json in order to use like that

var str_json = JSON.parse(str_for_json);

Now enjoy. Cheers!!