Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Created October 28, 2012 06:56
Show Gist options
  • Select an option

  • Save Radagaisus/3967923 to your computer and use it in GitHub Desktop.

Select an option

Save Radagaisus/3967923 to your computer and use it in GitHub Desktop.
parse_url
# Parses a URL string, using the DOM
#
# - href - full URL
# - host - sub.domain.tld:port
# - path - /stuff
# - protocol - https:
# - port - 80
# - search - unparsed query string
# - query - parsed query string
# - fullpath - path + query string
parse_url: (url) ->
a = document.createElement "a"
a.href = url
return a =
href : a.href
host : a.host.replace(/^www./, '')
# IE has a bug with leading slash on the path name,
# we therefore replace the start of the pathname with a slash.
# See http://stackoverflow.com/questions/616
path : a.pathname
protocol: a.protocol
port : if a.port is '' then '80' else a.port
search : a.search
query : @decode_query a.search.substr(1)
fullpath: a.href.substr(a.href.indexOf(a.host) + a.host.length)
# Parses a query string to an object
# Returns null if there's no query string.
decode_query: (q) ->
return null if not q
query = {}
pairs = q.split "&"
parts = (pair.split '=' for pair in pairs)
for part in parts when part.length is 2
query[part[0]] = decodeURI(part[1])
return query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment