Created
July 27, 2012 16:53
-
-
Save bunnymatic/3189131 to your computer and use it in GitHub Desktop.
simple url/query string parser coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Added preserve of the hash param
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested in FF/Chrome. It looks like the 'a' tag has slightly different attributes in these two browsers.