Skip to content

Instantly share code, notes, and snippets.

@gregdeane
Last active October 7, 2016 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregdeane/2c1f6b0998b9b3d60916832ae748ef23 to your computer and use it in GitHub Desktop.
Save gregdeane/2c1f6b0998b9b3d60916832ae748ef23 to your computer and use it in GitHub Desktop.
Parse URL
/**
 * Return url split into its parts
 * If `key` is passed, return that part of the url
 * If `key` is passed but not found, return all of the parts
 *
 * Allowed keys: "url", "scheme", "host", "port", "path", "query", "hash"
 *
 * @param {string} url - Url to parse
 * @param {string} key - "url", "scheme", "host", "port", "path", "query", "hash"
 * @returns {object|string} Url parts object or specific part value
 */
function getUrlParts(url, key) {
  var parseUrl = /([^:]+):\/\/([^:\/]+)(?::(\d+))?(?:\/#\/)?(?:([^?]*))?(?:\?([^#]*))?(?:#(.*))?$/,
      names = ['url', 'scheme', 'host', 'port', 'path', 'query', 'hash'],
      result = parseUrl.exec(url),
      urlParts = {};

  names.forEach(function (name, i) {
    urlParts[name] = (result[i] || '');
  });

  return urlParts[key] || urlParts;
}
/**
 * Return specific URL query value
 *
 * @param {string} query - Url query string (e.g. ?param1=xxxxx&param2=xxxxx&param3=xxxxx)
 * @param {string} key - Query key to look for (e.g. 'param1', 'param2', 'param3')
 * @returns {string|undefined} Query value or undefined
 */
function getUrlQueryParts(query, key) {
  var queryParts = {};

  // split by ampersand
  query = query.split('&');

  // build queryParts object
  query.forEach(function (q) {
    q = q.split('=');
    queryParts[q[0]] = q[1];
  });

  // depending on `key`, this will return a value or `undefined`
  // `undefined` is perfectly acceptable so don't add any checks here.
  return queryParts[key];
}
var url = 'https://merchant.google.zalando.com/#/test';
var domain = getUrlParts(url, 'host');
var parts = domain.split('.');

if (parts[1] !== 'solutions') {
  console.log('FAILED');
} else {
  console.log('SUCCESS');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment