Created
July 11, 2022 16:00
-
-
Save kiliman/fea1a83e4e48489475de60a5b270e6d1 to your computer and use it in GitHub Desktop.
Function to generate relative URL paths
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 getRelativePath(location: Location, relativePath: string) { | |
const base = new URL(`http://dummy${location.pathname}${location.search}`) | |
const relative = new URL(relativePath, base) | |
return `${relative.pathname}${relative.search}` | |
} | |
// path = /parent/child/?a=1 | |
const location = useLocation() | |
const relative = getRelativePath(location, '..?b=2') | |
// relative = /parent/?b=2 | |
/* | |
`.` always refers to *current folder* and `..` refers to *parent folder* | |
``` | |
/a/b/c/ . = /a/b/c/ .. = /a/b/ | |
/a/b/c . = /a/b/ .. = /a/ | |
/a/b/c ./d = /a/b/d ../d = /a/d | |
``` | |
It even handles search params properly. If you provide them, it will | |
overwrite existing search for current location. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment