I\'m trying to add a \"back to dir\" button at the top of a web page, which would redirect the user to the same URL, but with no filename in it.
For example, clickin
This one-liner also works:
document.URL.split('/').slice(0, -1).join('/')
The following gets directories, including the case where the last character is a slash.
document.URL.replace(/\/[^/]+\/?$/, '');
This effectively states the following (assuming they can be found in this order)
\/
: Find a "/"[^/]+
: Find one or more characters after it that are not "/"\/?
: Find an optional "/" after those character(s)$
: Find the end of the stringThen remove these by ''
, so we're left with the directory only.
Again, this assumes there is a slash present marking a directory and that this is not just a URL where the only slashes are within http://
.
/* to avoid query parameters, use pathname instead of href */
var l = document.location.pathname.split('/');
l.pop();
console.log(document.location.origin + l.join('/'));
console.log(new URL(document.URL));
you would get all object like this :
{
href:"https://yy.xx.id/index.php/5351/user/private/images%20%282%29.jpeg?forcedownload=1",
origin:"https://smi.kerjaindonesia.id",
protocol: "https:",
username: "",
password: "",
pathname: "index.php/5351/user/private/images%20%282%29.jpeg" ,
port: "" ,
protocol: "https:",
search: "?forcedownload=1"
}
Try the following, which takes into account both when the URL ends in a trailing slash and when it doesn't:
var currUrl = document.URL,
newUrl;
if (currUrl.charAt(currUrl.length - 1) === '/') {
newUrl = currUrl.slice(0, currUrl.lastIndexOf('/'));
newUrl = newUrl.slice(0, newUrl.lastIndexOf('/')) + '/';
} else {
newUrl = currUrl.slice(0, currUrl.lastIndexOf('/')) + '/';
}
console.log(newUrl);
Try this document.URL.substr(0,document.URL.lastIndexOf('/'))
It will work for sure!