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.
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.
Share Improve this question asked May 9, 2019 at 14:59 Franklin YuFranklin Yu 9,9587 gold badges50 silver badges60 bronze badges 5-
1
Why don't you append
www.example./
before your string and parse it ... – vaku Commented May 9, 2019 at 15:02 -
You could use
new URL('folder/file.ext?a=1&b=2#hash', 'http://dummy');
as a workaround. – Zlatko Commented May 9, 2019 at 15:04 - If you know what your relative URL's parameters roughly look like, meaning your identifiers '?' and '#' are unique, you could use basic JS and just split the relative URL string, stitch together your own JSON-Object with the data gained from that. – Stöger Commented May 9, 2019 at 15:06
- Thank you guys for quick response. This seems to be a stupid question then; please create an answer so I can give whoever credit and finish this question. (Or should I delete this question altogether? – Franklin Yu Commented May 9, 2019 at 15:06
-
1
This is a good question and hasn't been answered yet. @Zlatko This won't work when you have a relative URL with double dots (
..
) since these need to be preserved until the absolute URL is known. @Stöger Manual string transformations are brittle and should be delegated to a library. – mdcq Commented Sep 26, 2021 at 11:21
1 Answer
Reset to default 12This 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.