remove last directory in URL
Solution 1
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 http://jsfiddle.net/GWr7U/
Solution 2
By using this code remove the last element from the Url link.
url.substring(0, url.lastIndexOf('/'));
Solution 3
Another way to remove the end of directory path:
path.normalize(path.join(thePath, '..'));
Solution 4
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 :string
s for Javascript. Maybe you want different behaviour but you should at least consider these edge cases.
pascalhein
Updated on July 09, 2022Comments
-
pascalhein almost 2 years
I am trying to remove the last directory part of an URL. My URL looks like this:
https://my_ip_address:port/site.php?path=/path/to/my/folder
.When clicking on a button, I want to change this to
https://my_ip_address:port/site.php?path=/path/to/my
. (Remove the last part).I already tried
window.location.replace(/\/[A-Za-z0-9%]+$/, "")
, which results inhttps://my_ip_address:port/undefined
.What Regex should I use to do this?
-
Alexander Komarov about 7 yearsfor js: string removelastdir = url.substring(0, url.lastIndexOf('/'));
-
Alexander Tsepkov over 4 yearsThis solution is superior to the more upvoted/accepted answer. It's obvious just by looking at it, but I also created a short jsperf example to show this: jsperf.com/split-vs-lastindexof-2/1
-
Timmmm over 4 yearsThis is unnecessarily inefficient. It will work but it will be much slower than @Thrivan Mydeen's answer.
-
Nebulosar almost 3 yearsOr use the window: ` window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'))`