Created
October 28, 2012 06:56
-
-
Save Radagaisus/3967923 to your computer and use it in GitHub Desktop.
parse_url
This file contains hidden or 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
| # 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