Last active
August 29, 2015 14:03
-
-
Save datchley/766814180850eb10dceb to your computer and use it in GitHub Desktop.
Parse a URL string in it's various parts
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
| function parseUrl(url) { | |
| var _url = (url || window.location.href).match(/^(?:(https?:)\/\/)?([^\?\#\/\:]+)(?::(\d+))?([^\?\#]+)?(\?[^#]+)?(#[^\s]+)?$/), | |
| params = _url[5] || false; | |
| if (!_url.length) { | |
| // couldn't parse url string | |
| return false; | |
| } | |
| if (params && !/^$/.test(params)) { | |
| var pairs = params.replace(/^\?/,'').split('&'); | |
| params = {}; | |
| // console.log("pairs=%o", pairs); | |
| for (var i=0, l=pairs.length; i<l; i++) { | |
| var keyval = pairs[i].split('='); | |
| params[keyval[0]] = keyval[1]; | |
| } | |
| } | |
| return { | |
| source: url, | |
| protocol: _url[1], | |
| host: _url[2], | |
| port: _url[3], | |
| path: _url[4], | |
| query: _url[5], | |
| hash: _url[6], | |
| params: params | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment