Guest User

Querystring parsing

a guest
Sep 29th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const paragraph = 'foo=1&foo=2&foo=3&blah=a&blah=b';
  2. const regex = /([^=&]+)=([^&]*)/g
  3. const array = [...paragraph.matchAll(regex)]
  4.  
  5. const obj = array.reduce((q,[kv, key, value]) => {
  6.   q[key] = (q[key] ? q[key] + `,`: ``) + value
  7.   return q
  8. }, {});
  9.  
  10. const result = Object.keys(obj).map(a => `${a}=${obj[a]}`).join(`&`)
  11. console.log(result)
  12. // expected output: "foo=1,2,3&blah=a,b"
  13.  
Advertisement
Add Comment
Please, Sign In to add comment