Skip to content

Instantly share code, notes, and snippets.

@yoshuawuyts
Created July 20, 2016 13:47
Show Gist options
  • Save yoshuawuyts/eaae9ecef23aae38b4cab2656eeddbbb to your computer and use it in GitHub Desktop.
Save yoshuawuyts/eaae9ecef23aae38b4cab2656eeddbbb to your computer and use it in GitHub Desktop.
const reg = new RegExp("([^?=&]+)(=([^&]*))?", "g")
function qs (uri) {
const obj = {}
uri = uri.replace(/^.*\?/, '')
uri.replace(reg, map)
return obj
function map (a0, a1, a2, a3) {
obj[decodeURIComponent(a1)] = decodeURIComponent(a3)
}
}
console.log(qs('http:///foo/bar/#hello?world=bar'))
console.log(qs('/foo/bar/#hello?world=bar&foo=hey'))
console.log(qs('/foo/bar/#hello?world=bar&foo=hey&bbbbuuuub_foo=oi'))
@yoshuawuyts
Copy link
Author

Output:

❯ node qs.js
{ world: 'bar' }
{ world: 'bar', foo: 'hey' }
{ world: 'bar', foo: 'hey', bbbbuuuub_foo: '"oi"' }

@yoshuawuyts
Copy link
Author

Final version:

const reg = new RegExp("([^?=&]+)(=([^&]*))?", "g")
const decodeURIComponent = window.decodeURIComponent

module.exports = qs

// decode a uri into a kv representation :: str -> obj
function qs (uri) {
  const obj = {}
  uri.replace(/^.*\?/, '').replace(reg, map)
  return obj

  function map (a0, a1, a2, a3) {
    obj[decodeURIComponent(a1)] = decodeURIComponent(a3)
  }
}

@mantoni
Copy link

mantoni commented Jul 20, 2016

Here's a version without using a regular expression (not better, just different):

module.exports = (uri) => {
  const p = uri.indexOf('?')
  return p === -1 ? {} : uri.substring(p + 1).split('&').reduce((o, e) => {
    const p = e.indexOf('=')
    o[decodeURIComponent(e.substring(0, p))] = decodeURIComponent(e.substring(p + 1))
  }, {})
}

@rreusser
Copy link

Ah, good to know… looks like query strings are "are often used to carry identifying information in the form of key=value pairs", but nothing binding (seems?). See: https://tools.ietf.org/html/rfc3986#section-3.4 So lack of foo=bar&foo=baz (lists) and foo[bar]=baz (objects) compared to qs is a perfectly valid choice. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment