Suppose I have this query and want to convert into an object


output for this should be

article1: 'DRAFT',
article2: 'REVISION',
article3: 'DRAFT',
article16: 'READY'

Please review my code. Is this the right way to do perform this task?

let a = "a1.b2.article1=0&a2.article2=1&c3!article3=0&article16-abc=2";
let con = {'0':'DRAFT', '1':'REVISION', '2':'READY'}
let obj = {};
a = a.replace(/-abc/g, "");
a = a.replace(/[.!]/g, "&");
a = a.split("&").forEach((v, i) => {
    let b = v.split("=");
    if (b.length > 1) {

I'm wondering if there any optimized way to do this.


1 Answer 1


I suggest you use the standard query string syntax to avoid future problems. Because the weirder this query string gets, the more cases you'll have to add to this piece of code. And when a case that's not covered in your code appears, it will unexpectedly break your code.

Also, this used to be the way to parse query strings (i.e. split by &, loop through the items, split by =). Now, there is a built-in API, URLSearchParams, that parses query strings for you. It exists for both browser JS as well as NodeJS. It exposes several methods as well as methods that return iterables, which allow you to loop through the items.

  • \$\begingroup\$ Thank you for the answer but the question is not specific about URL parameters \$\endgroup\$ May 19, 2019 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.