I am trying to remove the last directory part of an URL. My URL looks like this:
.
When clicking on a button, I want to change this to
. (Remove the last part).
I already tried window.location.replace(/\/[A-Za-z0-9%]+$/, ""), which results in
.
What Regex should I use to do this?
65 Answers
By using this code remove the last element from the Url link.
url.substring(0, url.lastIndexOf('/')); 3 Explanation: Explode by "/", remove the last element with pop, join again with "/".
function RemoveLastDirectoryPartOf(the_url)
{ var the_arr = the_url.split('/'); the_arr.pop(); return( the_arr.join('/') );
}see fiddle
1Another way to remove the end of directory path:
path.normalize(path.join(thePath, '..')); Here is some code that correctly handles /, "", foo and /foo (returning /, "", foo, and / respectively):
function parentDirectory(dir: string): string { const lastSlash = dir.lastIndexOf('/'); if (lastSlash === -1) { return dir; } if (lastSlash === 0) { return '/'; } return dir.substring(0, lastSlash);
}Just remove the :strings for Javascript. Maybe you want different behaviour but you should at least consider these edge cases.
Sticking to native libraries, dirname could be helpful.
In node (backend)
const path = require('path')
let str='
console.log(path.dirname(n))
console.log(path.dirname(n)+'/')The output is
'
'In the Firefox browser (see MDN, Path Manupluation, OS.Path.dirname])
let str='
console.log(OS.path.dirname(n))
console.log(OS.path.dirname(n)+'/')Sorry but couldn't find anything for Chromium, but maybe I just didn't look hard enough.