Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@brianmcallister
Created September 12, 2014 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brianmcallister/94d89b3c50b2b9e98f6d to your computer and use it in GitHub Desktop.
Save brianmcallister/94d89b3c50b2b9e98f6d to your computer and use it in GitHub Desktop.
Parse query parameters.
# Parse the query string params.
# https://gist.github.com/brianmcallister/94d89b3c50b2b9e98f6d
#
# Examples
#
# If the query string is:
# test=test&foo&a=truee&bool=false&num=10
#
# parseQueryParams()
# #=> {"test": "test", "foo": "", "a": "truee", "bool": false, "num": 10}
#
# If the query string is:
# a=b=c&f&g=true%20&h=false
#
# parseQueryParams()
# #=> {"a": "b=c", "f": "", "g": "true ", "h": false}
#
# Returns an object of query string params.
parseQueryParams = ->
params = {}
return params unless window.location.search.length > 0
for part in window.location.search.slice(1).split '&'
eqlIndex = part.indexOf '='
if eqlIndex isnt -1
# Split on the first occurrence of '=', instead of using
# String::split. `key` should get everything before the first '=',
# and value should get everything after the first '=', minus the '='
# character itself.
key = part.slice 0, eqlIndex
value = part.slice eqlIndex + 1
else
# Some keys might not have values. Default to a blank string.
key = part
value = ''
# Decode.
value = decodeURIComponent value
# If something looks like it could be a boolean, convert it to a
# boolean.
lc = value.toLowerCase()
if lc is 'true'
params[key] = true
continue
if lc is 'false'
params[key] = false
continue
# If the parsed number is the same as the string 'number', convert
# the string into an actual number.
if "#{parseInt value, 10}" is value
params[key] = parseInt value, 10
continue
params[key] = value
return params
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment