Last active
August 29, 2015 14:00
-
-
Save lerouxb/11213541 to your computer and use it in GitHub Desktop.
Parse a URL and querystring.
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
| # This could be used as a client-side polyfill for node.js's url.parse() | |
| parseURL = (url, parseQuery) -> | |
| # http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript | |
| 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 or domain-relative urls shouldn't have host and such filled in | |
| if not url or url[0] == '/' and url.slice(0, 2) != '//' | |
| parsed.protocol = null | |
| parsed.host = null | |
| parsed.port = null | |
| parsed.hostname = null | |
| # http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost | |
| 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