I have a string in this format:
var x = "a=1; b=2; c=3; d=4"
and I would like to convert it to an object like this:
var y = {
a: "1",
b: "2",
c: "3",
d: "4"
}
Any ideas how to achieve that?
I have a string in this format:
var x = "a=1; b=2; c=3; d=4"
and I would like to convert it to an object like this:
var y = {
a: "1",
b: "2",
c: "3",
d: "4"
}
Any ideas how to achieve that?
This works in iE9+
var x = "a=1; b=2; c=3; d=4",
y = {};
x.split(';').map(function (i) {
return i.split('=')
}).forEach(function (j) {
y[j[0].trim()] = j[1]
});
If you are using Node.js v4+
let x = "a=1; b=2; c=3; d=4",
y = {}
x.split(';').map(i => i.split('=')).forEach(j => y[j[0].trim()] = j[1])
You could try this (not bullet proof, refer to comments):
var json, str;
str = 'a=1; b=2; c=3; d=4';
str = str.replace(/\s*;\s*/g, ',');
str = str.replace(/([^,]+)=([^,]+)/g, '"$1":"$2"');
str = '{' + str + '}';
json = JSON.parse(str);
document.write(
'<pre>' + JSON.stringify(json) + '</pre>'
);
" that occurs in the value. You also have to make sure to escape any escape sequences that have a special meaning in JSON and any occurrence of \ otherwise. Also this approach will fail if any of the values itself contains a ,.