// This snippet came from http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url // If was converted into a class to make sure that there is no conflicts with other functions. var URLPathInfo = { /** * Break apart any path into parts * 'http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10' -> * { * "host": "example.com", * "port": "12345", * "search": { * "startIndex": "1", * "pageSize": "10" * }, * "path": "/blog/foo/bar", * "protocol": "http:" * } */ getPathInfo: function (path) { // create a link in the DOM and set its href var link = document.createElement('a'); link.setAttribute('href', path); // return an easy-to-use object that breaks apart the path return { host: link.hostname, // 'example.com' port: link.port, // 12345 search: URLPathInfo.processSearchParams(link.search), // {startIndex: 1, pageSize: 10} path: link.pathname, // '/blog/foo/bar' protocol: link.protocol // 'http:' } }, /** * Convert search param string into an object or array * '?startIndex=1&pageSize=10' -> {startIndex: 1, pageSize: 10} */ processSearchParams: function (search, preserveDuplicates) { // return blank if nothing is in the search if(!search) return ''; // option to preserve duplicate keys (e.g. 'sort=name&sort=age') preserveDuplicates = preserveDuplicates || false; // disabled by default var outputNoDupes = {}; var outputWithDupes = []; // optional output array to preserve duplicate keys // sanity check if(!search) throw new Error('processSearchParams: expecting "search" input parameter'); // remove ? separator (?foo=1&bar=2 -> 'foo=1&bar=2') search = search.split('?')[1]; // split apart keys into an array ('foo=1&bar=2' -> ['foo=1', 'bar=2']) search = search.split('&'); // separate keys from values (['foo=1', 'bar=2'] -> [{foo:1}, {bar:2}]) // also construct simplified outputObj outputWithDupes = search.map(function(keyval){ var out = {}; keyval = keyval.split('='); out[keyval[0]] = keyval[1]; outputNoDupes[keyval[0]] = keyval[1]; // might as well do the no-dupe work too while we're in the loop return out; }); return (preserveDuplicates) ? outputWithDupes : outputNoDupes; } };