0

I have this string:

ROZ=misparey_batim&CL=rechovot

I need to convert this string:

"{ROZ:'misparey_batim', CL:'rechovot'}"

How can I convert it using javascript or jquery?

Michael
  • 12,788
  • 49
  • 133
  • 253

2 Answers2

3

var inputstring = "ROZ=misparey_batim&CL=rechovot";
console.log(JSON.parse('{"' + decodeURI(inputstring).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'));
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
1

Simplest approach:

const keyVals = string.split('&');
const results = {};
keyVals.forEach(kv => {
   kv = kv.split('=');
   results[kv[0]] = kv[1];
});

But personally I'd just search for a query string parser Parse query string in JavaScript

PiniH
  • 1,871
  • 11
  • 20