For absolute URL we can parse with new URL(str)
; for relative URL with base URL we can have new URL(path, base)
. How do I parse a relative URL without a base URL? For example, folder/file.ext?a=1&b=2#hash
should be parsed into
{ pathname: "folder/file.ext", search: "?a=1&b=2", hash: "#hash" }
Third-party library is fine, but I prefer built-in libraries and functions. Prefer cross-platform (browser/Node.js) solutions. No need for IE.
Advertisement
Answer
This is a great question. Currently, manipulating relative URLs without needing a base isn’t supported by the URL Standard. Using a dummy base doesn’t always work, since a relative URLs with dot segments like ../path
would be resolved against the base without the possibility to recover it again later. It’s unfortunate that this hasn’t been thought of in the URL Standard. Though there is some discussion to add it in #531.
In the meanwhile, check out reurl which is a library that allows you to manipulate relative URLs without resorting to brittle manual string manipulation.