remove last directory in URL

47,715

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 :strings for Javascript. Maybe you want different behaviour but you should at least consider these edge cases.

Share:
47,715
pascalhein
Author by

pascalhein

Updated on July 09, 2022

Comments

  • pascalhein
    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 in

    https://my_ip_address:port/undefined.

    What Regex should I use to do this?

  • Alexander Komarov
    Alexander Komarov about 7 years
    for js: string removelastdir = url.substring(0, url.lastIndexOf('/'));
  • Alexander Tsepkov
    Alexander Tsepkov over 4 years
    This 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
    Timmmm over 4 years
    This is unnecessarily inefficient. It will work but it will be much slower than @Thrivan Mydeen's answer.
  • Nebulosar
    Nebulosar almost 3 years
    Or use the window: ` window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'))`