Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a relative URL without base URL in JavaScript

Tags:

javascript

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.

like image 314
Franklin Yu Avatar asked Nov 07 '22 17:11

Franklin Yu


1 Answers

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.

like image 112
philmcole Avatar answered Nov 14 '22 23:11

philmcole