Skip to content

Instantly share code, notes, and snippets.

@danny-andrews
Created September 6, 2017 18:58
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 danny-andrews/cc40afc4c29afaa1adc0f279e6f880fb to your computer and use it in GitHub Desktop.
Save danny-andrews/cc40afc4c29afaa1adc0f279e6f880fb to your computer and use it in GitHub Desktop.
URL utils that I use in literally every app
const removeTrailingSlash = path => path.replace(/\/$/, '');
const ensureTrailingSlash = path => `${removeTrailingSlash(path)}/`;
// Universal usage (no reliance on `document`)
const parseUrl = (href) => {
const match = href.match(/^(https?:)\/\/(([^:/?#]*)(?::([0-9]+))?)([/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7],
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment