Remove Last Directory in Url

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?

6

5 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

1

Another 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest