Skip to content

Instantly share code, notes, and snippets.

@kiliman
Created July 11, 2022 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiliman/fea1a83e4e48489475de60a5b270e6d1 to your computer and use it in GitHub Desktop.
Save kiliman/fea1a83e4e48489475de60a5b270e6d1 to your computer and use it in GitHub Desktop.
Function to generate relative URL paths
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