Design & Download
Your JS Library
in Seconds!!!

Snippet: parseURL() - Parse Any URL

Written by Christopher West (cwest) on January 08, 2016.
Parse a complete or incomplete URL.
function parseURL(opt_url) {
  var elem = document.createElement('a'),
      result = {
        params: parseQS(elem.href = opt_url = opt_url == undefined ? __global.location.href : opt_url),
        toString: function() {
          return href;
        }
      };
  walk(elem, function(value, key) {
    if (/^(hash|href|port|protocol|(user|path|host)(name)?|search|password)$/.test(key)) {
      result[key] = value;
    }
  }, 1);
  return result;
}

parseURL() API Documentation

Parse a complete or incomplete URL.

Parameters

  1. opt_url {string=}:
    Optional. Defaults to window.location.href. The URL that will be parsed and turned into a complete URL if it is incomplete.

Returns

An object containing all of the following:
  • .href:
    The full URL (eg. 'http://google.com/search?q=cool+stuff&time=918239823').
  • .protocol:
    A string containing the protocol scheme of the URL, including the final ':' (eg. 'http:).
  • .host:
    A string containing the host, that is the hostname and if a port was specified, a ':' and the port of the URL (eg. 'google.com' or 'google.com:293').
  • .hostname:
    A string containing the domain of the URL (eg. 'google.com').
  • .port:
    A string containing the port number of the URL, but ONLY IF IT WAS SPECIFIED (eg. '' or '293').
  • .pathname:
    A string containing an initial '/' followed by the path of the URL (eg. '/search').
  • .search:
    A string containing a '?' followed by the parameters of the URL (eg. '?q=cool+stuff&time=918239823'). Also known as "querystring".
  • .hash:
    A string containing a '#' followed by the fragment identifier of the URL (eg. '#top').
  • .username:
    A string containing the username specified before the domain name (eg. 'jsmith' taken from 'ftp://jsmith:top_secret@example.com').
  • .password:
    A string containing the password specified before the domain name (eg. 'top_secret' taken from 'ftp://jsmith:top_secret@example.com').
  • .params:
    An object containing all of the query string parameters as parsed by parseQS().
  • .toString():
    When called this returns the value of href in the object.