100

I'm trying to get the current directory of the file in Javascript so I can use that to trigger a different jquery function for each section of my site.

if (current_directory) = "example" {
var activeicon = ".icon_one span";
};
elseif (current_directory) = "example2" {
var activeicon = ".icon_two span";
};
else {
var activeicon = ".icon_default span";
};

$(activeicon).show();
...

Any ideas?

12 Answers 12

101

window.location.pathname will get you the directory, as well as the page name. You could then use .substring() to get the directory:

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
2
60

In Node.js, you could use:

console.log('Current directory: ' + process.cwd());
3
  • Please describe more.
    – TigerTV.ru
    Mar 11, 2018 at 23:19
  • this answer for nodejs platform. you should tell where you run javascript, before answer on this question. Mar 13, 2018 at 10:11
  • For eg. in the main server.js file as constant in any case ...
    – Fabrice T
    Sep 19, 2020 at 20:10
22

You can use window.location.pathname.split('/');

That will produce an array with all of the items between the /'s

18

complete URL

If you want the complete URL e.g. http://website/basedirectory/workingdirectory/ use:

var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

local path

If you want the local path without domain e.g. /basedirectory/workingdirectory/ use:

var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

In case you don't need the slash at the end, remove the +1 after location.lastIndexOf("/")+1.

directory name

If you only want the current directory name, where the script is running in, e.g. workingdirectory use:

var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);
3
  • 2
    location causes Google Chrome to reload the page, change the variable name to something else like location1
    – mparkuk
    Nov 15, 2016 at 10:40
  • Saved me big time with this! Thank you
    – Shadoninja
    May 31, 2020 at 22:22
  • You're my angel for today!
    – hubert17
    Jun 19, 2021 at 23:29
16

This will work for actual paths on the file system if you're not talking the URL string.

var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
1
  • var path = document.location.pathname; var dir = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
    – gtzinos
    Mar 20, 2016 at 16:10
10

For both / and \:

window.location.pathname.replace(/[^\\\/]*$/, '');

To return without the trailing slash, do:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');
1
  • This works in IE<9, while the answers using .lastIndexOf do not. +1 for this reason. May 13, 2015 at 19:31
8

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
1
  • Trying to remove my down vote but SO won't let me because I voted on this recently. that makes a lot of sense...
    – SikoSoft
    Nov 14, 2019 at 23:03
4

An interesting approach to get the dirname of the current URL is to make use of your browser's built-in path resolution. You can do that by:

  1. Create a link to ., i.e. the current directory
  2. Use the HTMLAnchorElement interface of the link to get the resolved URL or path equivalent to ..

Here's one line of code that does just that:

Object.assign(document.createElement('a'), {href: '.'}).pathname

In contrast to some of the other solutions presented here, the result of this method will always have a trailing slash. E.g. running it on this page will yield /questions/3151436/, running it on https://stackoverflow.com/ will yield /.

It's also easy to get the full URL instead of the path. Just read the href property instead of pathname.

Finally, this approach should work in even the most ancient browsers if you don't use Object.assign:

function getCurrentDir () {
    var link = document.createElement('a');
    link.href = '.';
    return link.pathname;
}
1

If you want the complete URL e.g. website.com/workingdirectory/ use: window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, '');

0

window.location.pathname

0

I find this way pretty reliable to find the url of current page, by using the standard URL object. Fits well to create new URLs, using relative and absolute paths

url = window.location
console.log(url);
//strip pagename from pathname
currentdir = new URL(url.pathname.replace( /[^\/]*$/, ''), url.origin);
//now make new paths relative to currentdir
console.log(new URL("/dir1/dir2/hello.html", currentdir));
console.log(new URL("../../dir1/dir2/hello.html", currentdir));
console.log(new URL("../dir1/dir2/hello.html", currentdir));
console.log(new URL("./dir1/dir2/hello.html", currentdir));
console.log(new URL("dir1/dir2/hello.html", currentdir));
currentdir.port = 1234;
console.log(new URL("dir1/dir2/hello.html", currentdir));

There are current outputs expected, supposing the current page is
https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html

https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html
"currentdir = https://interactive-examples.mdn.mozilla.net/pages/js/"
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net:1234/pages/js/dir1/dir2/hello.html
0

In Deno, you can use Deno.cwd():

const currentWorkingDirectory = Deno.cwd();
console.log(currentWorkingDirectory);

In Node.js, you can use process.cwd():

const currentWorkingDirectory = process.cwd();
console.log(currentWorkingDirectory);

In browser client code, you can use location.pathname:

const pathname = location.pathname;
console.log(pathname);

//Beware that the pathname might not correspond to a file
//The `|| 1` handles the case when pathname is just "/", making it return "/"
const assumedDirectory = pathname.substring(0, (pathname.lastIndexOf("/") || 1));
console.log(assumedDirectory);

P.S.:

To make your code work both in Deno & Node.js, you could do something like:

function cwd() {
  try {
    return process.cwd();
  }
  catch (error) {
    if (error instanceof ReferenceError) {
      return Deno.cwd();
    }
    else {
      throw error;
    }
  }
}

// Or otherwise just:
((typeof process === "object") ? process : Deno).cwd();

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.