A simple URL regex that can handle most "properly" formed URLs, and some URIs. It features named groups to easily destruct matches. URIs can use relative paths (../
and ./
) to resources.
let url = "https://username:password@example.org:8080/path/to/resource?query=term&query=terms#fragment";
let regex = /{{ URL RegEx }}/i;
let { href, origin, protocol, scheme, username, password, host, hostname, port, pathname, search, hash } = regex.exec(url).groups;
// href → "https://username:password@example.org:8080/path/to/resource?query=term&query=terms#fragment"
// origin → "https://"
// protocol → "https:"
// scheme → "https"
// username → "username"
// password → "password"
// host → "example.org:8080"
// hostname → "example.org"
// port → "8080"
// pathname → "/path/to/resource"
// search → "?query=term&query=terms"
// hash → "#fragment"