Alexander Farber
Alexander Farber

Reputation: 23008

How to get the directory part of current URL in JavaScript?

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, clicking that button while viewing the URL

http://example.com/somedir/button.html

would redirect you to the

http://example.com/somedir/

So I've created the following code:

<html>
<body>

<input type="button"
value="back to dir"
onclick="top.location=document.URL.replace(/[^\\]*$/, '')">

</body>
</html>

but I'm missing the correct code, which would shave away the filename from the current URL in document.URL

Does anybody have a good idea here please?

Here is the JSFiddle link: http://jsfiddle.net/afarber/PERBY/

And I'd prefer not to use jQuery this one time.

Upvotes: 18

Views: 25975

Answers (6)

robby dwi hartanto
robby dwi hartanto

Reputation: 435

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"
}

Upvotes: 4

Brett Zamir
Brett Zamir

Reputation: 14355

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)

  1. \/: Find a "/"
  2. [^/]+: Find one or more characters after it that are not "/"
  3. \/?: Find an optional "/" after those character(s)
  4. $: Find the end of the string

Then 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://.

Upvotes: 1

jbyrd
jbyrd

Reputation: 5595

This one-liner also works:

document.URL.split('/').slice(0, -1).join('/')

Upvotes: 4

Abdul Rauf
Abdul Rauf

Reputation: 972

Try this document.URL.substr(0,document.URL.lastIndexOf('/'))

It will work for sure!

Upvotes: 33

Derek Henderson
Derek Henderson

Reputation: 9706

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);

Upvotes: 0

Hilson Shrestha
Hilson Shrestha

Reputation: 19

/* to avoid query parameters, use pathname instead of href */
var l = document.location.pathname.split('/');
l.pop();
console.log(document.location.origin + l.join('/'));

Upvotes: 1

Related Questions