如何在Javascript中获取当前目录名称?

101

我正在尝试使用Javascript获取文件的当前目录,以便我可以使用它来触发我的网站每个部分的不同jquery函数。

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

有什么想法吗?

12个回答

102

window.location.pathname会获取目录和页面名称。您可以使用.substring()来获取目录:

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

我的Joomla网站生成的URL如下:http://localhost/sub/sub/sub/index.php/ali-mm-d#tab2(还有其他奇怪的东西)因此,这种方法并不是生成目录,而是:http://localhost/sub/sub/sub/index.php - dsdsdsdsd
请注意:如果 loc === '/',则 dir === '' - raphinesse

61

在Node.js中,您可以使用:

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

请提供更详细的描述。 - TigerTV.ru
在回答这个问题之前,你应该告诉我你在哪里运行JavaScript,这个问题是针对Node.js平台的。 - philip brodovsky
例如,在主server.js文件中,无论如何都要作为常量… - Fabrice T

22
你可以使用window.location.pathname.split('/');
这将产生一个在/之间的所有项的数组。

19

完整的网址

如果您需要获取完整的网址,例如http://website/basedirectory/workingdirectory/,请使用以下代码:

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

本地路径

如果您想获得不带域名的本地路径,例如/basedirectory/workingdirectory/,请使用:

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

如果您不需要末尾的斜杠,请删除location.lastIndexOf("/") + 1后面的+1

目录名称

如果您只想要当前脚本正在运行的目录名称,例如workingdirectory,请使用:

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

2
位置会导致Google Chrome重新加载页面,请将变量名称更改为其他名称,例如location1。 - mparkuk
这个真的帮了我大忙!谢谢你。 - Shadoninja
你今天是我的天使! - hubert17

16

如果你说的不是URL字符串,那么这对于文件系统上的实际路径可以起作用。

var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));

var path = document.location.pathname;var dir = path.substring(path.indexOf('/'), path.lastIndexOf('/')); 变量路径=文档位置.路径名;变量目录=路径.子字符串(路径.索引(" / "), 路径.最后索引(" / ")); - gtzinos

10

对于 / 和 \ 两个符号:

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

要返回不带尾随斜杠,请执行以下操作:

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

这在IE<9中可行,而使用.lastIndexOf的答案则不可行。因此+1。 - thunderblaster

8
这个一行代码很有效:
var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

尝试取消我的踩但 SO 不允许我,因为我最近投票了。这很有道理... - SikoSoft

4
利用浏览器内置的路径解析功能来获取当前URL的dirname是一种有趣的方法。您可以通过以下步骤实现:
  1. 创建一个指向 . ,即当前目录的链接
  2. 使用链接的HTMLAnchorElement接口获取与 . 等效的已解析URL或路径。
下面是一行代码,实现了上述过程:
Object.assign(document.createElement('a'), {href: '.'}).pathname

与其他解决方案不同的是,此方法的结果始终具有尾随斜杠。例如,在此页面上运行它将产生/questions/3151436/,在https://stackoverflow.com/上运行它将产生/
获取完整的URL也很容易,只需读取href属性而不是pathname即可。
最后,如果您不使用Object.assign,这种方法应该可以在即使是最古老的浏览器中也能正常工作。
function getCurrentDir () {
    var link = document.createElement('a');
    link.href = '.';
    return link.pathname;
}

1
如果你想要完整的URL,例如website.com/workingdirectory/,请使用:window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, '');

0
在Deno中,您可以使用Deno.cwd()
const currentWorkingDirectory = Deno.cwd();
console.log(currentWorkingDirectory);

在Node.js中,您可以使用process.cwd()
const currentWorkingDirectory = process.cwd();
console.log(currentWorkingDirectory);

在浏览器客户端代码中,您可以使用{{link1: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.:

为了让你的代码在Deno和Node.js中都能运行,你可以这样做:
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接