remove last directory in URL

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/


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.


Another way to remove the end of directory path:

path.normalize(path.join(thePath, '..'));

By using this code remove the last element from the Url link.

url.substring(0, url.lastIndexOf('/'));