admin管理员组

文章数量:1133893

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?

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?

Share Improve this question edited Apr 18, 2023 at 8:14 jps 22.3k16 gold badges87 silver badges102 bronze badges asked Jun 30, 2010 at 16:43 user380303user380303 1,1512 gold badges7 silver badges5 bronze badges
Add a comment  | 

12 Answers 12

Reset to default 105

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('/'));

In Node.js, you could use:

console.log('Current directory: ' + process.cwd());

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

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

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

jQuery

// complete URL
$(location).attr("href");
// local path
$(location).attr("pathname");

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('/'));

For both / and \:

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

To return without the trailing slash, do:

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

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

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

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

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

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

window.location.pathname

本文标签: jqueryHow can I get the current directory name in JavascriptStack Overflow