gabrysiak
10/15/2014 - 8:42 PM

Javascript function that returns parsed URL object

Javascript function that returns parsed URL object

/**
 * Parse url
 * @param  {string} url Url string
 * @return {object}     Parsed url object
 *
 * Example Use:
 * var parsedUrl = parseURL('http://drive.google.com/search');
 *
 * parsedUrl {
 *   domain: "drive.google.com",
 *   host: "google",
 *   parentDomain: "google.com",
 *   path: "search",
 *   protocol: "http",
 *   subdomain: "drive",
 *   tld: "com"
 * }
 *
 */

function parseURL(url){
    var parsedUrl = {}

    if ( url == null || url.length == 0 )
        return parsedUrl;

    var protocol = url.indexOf('://'),
        remainingUrl = url.substr(protocol + 3, url.length),
        domain = remainingUrl.indexOf('/');

    parsedUrl.protocol = url.substr(0,protocol);

    domain = domain == -1 ? remainingUrl.length - 1 : domain;
    parsedUrl.domain = remainingUrl.substr(0, domain);
    parsedUrl.path = domain == -1 || domain + 1 == remainingUrl.length ? null : remainingUrl.substr(domain + 1, remainingUrl.length);

    var domainParts = parsedUrl.domain.split('.');
    switch ( domainParts.length ){
        case 2:
          parsedUrl.subdomain = null;
          parsedUrl.host = domainParts[0];
          parsedUrl.tld = domainParts[1];
          break;
        case 3:
          parsedUrl.subdomain = domainParts[0];
          parsedUrl.host = domainParts[1];
          parsedUrl.tld = domainParts[2];
          break;
        case 4:
          parsedUrl.subdomain = domainParts[0];
          parsedUrl.host = domainParts[1];
          parsedUrl.tld = domainParts[2] + '.' + domainParts[3];
          break;
    }

    parsedUrl.parentDomain = parsedUrl.host + '.' + parsedUrl.tld;

    return parsedUrl;
}