Skip to content

Instantly share code, notes, and snippets.

@lerouxb
Created May 8, 2015 10:04
Show Gist options
  • Select an option

  • Save lerouxb/aa99ea75cc23ce73f813 to your computer and use it in GitHub Desktop.

Select an option

Save lerouxb/aa99ea75cc23ce73f813 to your computer and use it in GitHub Desktop.
parseURL = (url, parseQuery) ->
parser = document.createElement('a')
parser.href = url
parsed =
protocol: parser.protocol
host: parser.host
hostname: parser.hostname
port: parser.port
pathname: parser.pathname
hash: parser.hash
search: parser.search
query: query
# blank, domain-relative and hash-link urls shouldn't have host and such
# filled in
if not url or url[0] in ['/', '#'] and url.slice(0, 2) != '//'
parsed.protocol = null
parsed.host = null
parsed.port = null
parsed.hostname = null
# hash-links shouldn't have pathname either
if url and url[0] == '#'
parsed.pathname = null
if parseQuery
query = {}
if parser.search and parser.search[0] == '?'
search = parser.search.slice(1)
.replace(/&+/g, '&') # remove blank vars
.replace(/^&/, '') # remove leading & chars
.replace(/&$/, '') # remove trailing & chars
pairs = search.split('&')
for pair in pairs
parts = pair.split('=')
continue unless parts.length > 1 # ignore broken ones
key = decodeURIComponent parts[0]
val = parts.slice(1).join('=') # keep unescaped = chars in values
query[key] = decodeURIComponent val
parsed.query = query
parsed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment