Skip to content

Instantly share code, notes, and snippets.

@brianmcallister
Created September 12, 2014 15:11
Show Gist options
  • Select an option

  • Save brianmcallister/94d89b3c50b2b9e98f6d to your computer and use it in GitHub Desktop.

Select an option

Save brianmcallister/94d89b3c50b2b9e98f6d to your computer and use it in GitHub Desktop.

Revisions

  1. brianmcallister revised this gist Sep 12, 2014. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions params.coffee
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,5 @@
    # Parse the query string params.
    # https://gist.github.com/brianmcallister/94d89b3c50b2b9e98f6d
    #
    # Examples
    #
  2. brianmcallister created this gist Sep 12, 2014.
    61 changes: 61 additions & 0 deletions params.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    # Parse the query string params.
    #
    # 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