Skip to content

Instantly share code, notes, and snippets.

@proprietary
Created January 26, 2016 06:15
Show Gist options
  • Save proprietary/304b30517d6220d2cfc8 to your computer and use it in GitHub Desktop.
Save proprietary/304b30517d6220d2cfc8 to your computer and use it in GitHub Desktop.
utility functions for query strings in javascript
function serializeQuery (queryObj) {
return '?' + Object.keys(queryObj)
.reduce(function (r, q) {
r.push(encodeURIComponent(q) + '=' + encodeURIComponent(queryObj[q]))
return r
}, [])
.join('&')
}
function readQuery (queryStr_) {
let queryStr = queryStr_[0] === '?' ? queryStr_.slice(1) : queryStr_
return queryStr.split('&')
.map(function (n) {
return n.split('=')
})
.reduce(function (x, y) {
return Object.assign(x, {
[decodeURIComponent(y[0])]: decodeURIComponent(y[1] || '')
})
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment