52

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?

6
  • 1
    You could also just add /../. LOL just joking, here's the real deal
    – HamZa
    May 25, 2013 at 14:35
  • 1
    @HamZaDzCyberDeV I am ignoring . in the path to avoid injection. But thanks for your link!
    – pascalhein
    May 25, 2013 at 14:36
  • @HamZaDzCyberDeV Somehow I don't get how to use replace: window.location.replace(/(.*)\/.*/,"\1"); results in https://my_ip_address:port/(.*)\/.*/
    – pascalhein
    May 25, 2013 at 14:37
  • Try something like this with a $.
    – HamZa
    May 25, 2013 at 14:44
  • do you HAVE TO use regex? There are other methods also.
    – Sharky
    May 25, 2013 at 14:48

6 Answers 6

91

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

url.substring(0, url.lastIndexOf('/'));
4
  • 4
    for js: string removelastdir = url.substring(0, url.lastIndexOf('/')); Feb 27, 2017 at 14:48
  • 2
    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 Sep 9, 2019 at 20:01
  • Or use the window: ` window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'))`
    – Nebulosar
    May 13, 2021 at 9:43
  • How would you alter this code to allow for more than one element to be removed? For example: https://my_ip_address:port/site.php?path=/path/to/my/folder down to https://my_ip_address:port/site.php?path=/path/to? Sep 15, 2022 at 13:21
51

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/

1
  • 5
    This is unnecessarily inefficient. It will work but it will be much slower than @Thrivan Mydeen's answer.
    – Timmmm
    Oct 10, 2019 at 15:08
7

Another way to remove the end of directory path:

path.normalize(path.join(thePath, '..'));
1
  • This will not work with urls https:// becomes https:/ May 31 at 9:22
4

The simplest way I suggest to use is the mix of split, slice and join:

const baseUrl = 'https://my_ip_address:12345/site.php?path=/path/to/my/folder';
const newUrl = baseUrl.split('/').slice(0, -1).join('/');

The above code has one problem - when the path ends with the slash / it will just remove the slash without removing the last path chunk. We can solve this by adding .filter(Boolean) before .slice(0, -1) but then if the URL has the protocol it will replace // with /.

So in more complex situations I suggest to use this safe option:

const baseUrl = 'https://my_ip_address:12345/site.php?path=/path/to/my/folder';

function removeLastDirectoryFromUrlSearchParam(baseUrl, paramName = 'path') {
  const url = new URL(baseUrl);
  const params = new URLSearchParams(url.search);
  const path = params.get(paramName);
  params.set(paramName, path.split('/').filter(Boolean).slice(0, -1).join('/'));
  url.search = params.toString();
  return url.toString();
}

const newUrl = removeLastDirectoryFromUrlSearchParam(baseUrl);
3

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.

0

Sticking to native libraries, dirname could be helpful.


In node (backend)

const path = require('path')
let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
console.log(path.dirname(n))
console.log(path.dirname(n)+'/')

The output is

'https://my_ip_address:port/site.php?path=/path/to/my'
'https://my_ip_address:port/site.php?path=/path/to/my'

In the Firefox browser (see MDN, Path Manupluation, OS.Path.dirname])

let str='https://my_ip_address:port/site.php?path=/path/to/my/folder'
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 and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.