Created
February 21, 2020 15:06
-
-
Save joaocarmo/feaf7ef1cfdb9491c9f1e6a8990d9113 to your computer and use it in GitHub Desktop.
A URL parsing function mostly compatible with the URL() constructor for browser's that don't support it
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
function parseUrl(url = '') { | |
// Make it compatible with the URL() constructor | |
const parsed = { | |
href: '', | |
origin: '', | |
protocol: '', | |
username: '', | |
password: '', | |
host: '', | |
hostname: '', | |
port: '', | |
pathname: '', | |
search: '', | |
searchParams: {}, | |
hash: '', | |
}; | |
/* | |
URI Generic Syntax | |
Source: https://tools.ietf.org/html/rfc3986#appendix-B | |
*/ | |
const regexUrl = /^(?:(?:(([^:\/#\?]+:)?(?:(?:\/\/)(?:(?:(?:([^:@\/#\?]+)(?:\:([^:@\/#\?]*))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((?:\/?(?:[^\/\?#]+\/+)*)(?:[^\?#]*)))?(\?[^#]+)?)(#.*)?/; | |
if (url) { | |
const parsedArr = regexUrl.exec(url); | |
parsed.href = parsedArr[0]; | |
parsed.origin = parsedArr[1]; | |
parsed.protocol = parsedArr[2]; | |
parsed.username = parsedArr[3]; | |
parsed.password = parsedArr[4]; | |
parsed.host = parsedArr[5]; | |
parsed.hostname = parsedArr[6]; | |
parsed.port = parsedArr[7]; | |
parsed.pathname = parsedArr[8]; | |
parsed.search = parsedArr[9]; | |
parsed.hash = parsedArr[10]; | |
} | |
return parsed; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment