Skip to content

Instantly share code, notes, and snippets.

@Lokua
Last active January 19, 2016 11:58
Show Gist options
  • Save Lokua/46422ba5877f979bde89 to your computer and use it in GitHub Desktop.
Save Lokua/46422ba5877f979bde89 to your computer and use it in GitHub Desktop.
query string script
export default {
/**
* Parse query string from path into POJO. If true is
* passed as 2nd argument, returns two member array
* of POJO and the query string portion
*
* @example
* ```js
* let path = 'http://foo.com/bar?a=1&b=2&c=3'
*
* qs.parse(path)
* //=> { a: 1, b: 2, c: 3 }
*
* qs.parse(path, true)
* //=> [ { a: 1, b: 2, c: 3 }, '?a=1&b=2&c=3' ]
* ```
*
* @param {String} path
* @param {Boolean} both=false
* @return {Object|Array}
*/
parse(path, both=false) {
path = decodeURIComponent(path)
let indexOf = path.indexOf('?')
let queryString = indexOf > -1 ? path.slice(indexOf) : ''
let query = {}
queryString.slice(1).split('&').forEach(segment => {
if (segment) {
let pair = segment.split('=')
query[pair[0]] = pair[1]
}
})
return both ? [query, queryString] : query
},
/**
* Convert POJO into query string
*
* @example
* ```js
* let o = { a: 1, b: 2, c: 3 }
*
* qs.stringify(o)
* //=> '?a=1&b=2&c=3'
* ```
*
* @param {Object} obj hash
* @return {String} query string
*/
stringify(obj) {
return '?' + Object.keys(obj).map(key => `${key}=${obj[key]}`).join('&')
},
/**
* Return array split at ?
*
* @param {String} path
* @return {Array}
*/
split(path) {
return path.split('?')
},
/**
* Remove query string from `path`
*
* @param {String} path
* @return {String} `path` without query string
*/
strip(path) {
path = decodeURIComponent(path)
if (path === 'undefined') return ''
const i = path.indexOf('?')
return i > -1 ? path.slice(0, i) : path
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment