Skip to content

Instantly share code, notes, and snippets.

@bunnymatic
Created July 27, 2012 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bunnymatic/3189131 to your computer and use it in GitHub Desktop.
Save bunnymatic/3189131 to your computer and use it in GitHub Desktop.
simple url/query string parser coffeescript
class QueryStringParser
constructor: (url) ->
@query_params = {}
if !document || !document.createElement
throw 'This needs to be run in an HTML context with a document.'
parser = document.createElement('a')
parser.href = url
@url = url
if (parser.origin)
@origin = parser.origin
else
@origin = [parser.protocol, '//', parser.host].join('')
@protocol = parser.protocol
@pathname = parser.pathname
@hash = parser.hash
_that = this
_.each parser.search.substr(1).split('&'), (params) ->
kv = params.split('=')
_that.query_params[kv[0]] = kv[1]
toString: ->
q = _.compact(_.map(@query_params, (v,k) ->
if (typeof v != 'undefined') && (v != null)
[k,v].join('=')
)).join('&')
bits = [ @origin, @pathname ].join('')
if q
bits += "?" + q
if @hash
bits += @hash
bits
@bunnymatic
Copy link
Author

Tested in FF/Chrome. It looks like the 'a' tag has slightly different attributes in these two browsers.

@bunnymatic
Copy link
Author

Added preserve of the hash param

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