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
  • 13,950
  • 57
  • 145
  • 288

2 Answers2

3

var inputstring = "ROZ=misparey_batim&CL=rechovot";
console.log(JSON.parse('{"' + decodeURI(inputstring).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}'));
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
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,901
  • 13
  • 20