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);
/../
. LOL just joking, here's the real deal.
in the path to avoid injection. But thanks for your link!replace
:window.location.replace(/(.*)\/.*/,"\1");
results inhttps://my_ip_address:port/(.*)\/.*/
$
.