Created
September 6, 2017 18:58
-
-
Save danny-andrews/cc40afc4c29afaa1adc0f279e6f880fb to your computer and use it in GitHub Desktop.
URL utils that I use in literally every app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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