Current Path | Result |
---|---|
/a/b/c |
/a/b |
/a/b |
/a |
/a |
/ |
/ |
/ (stays) |
- .filter(Boolean) cleans out empty strings, like the one before a in /a.
- .pop() knocks off the last piece.
- Reconstructs the path and falls back to / if it’s empty.
function goUp(){ | |
let parts = window.location.pathname.split('/').filter(Boolean); | |
parts.pop(); | |
let newPath = '/' + parts.join('/'); | |
window.location.href = newPath || '/'; | |
} | |
// goUp() will take you one level up. |
window.location.href = '/' + window.location.pathname.split('/').filter(Boolean).slice(0, -1).join('/'); |