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

时间:2010-06-30 16:43:45

标签: javascript jquery

我正在尝试使用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();
...

有什么想法吗?

11 个答案:

答案 0 :(得分:76)

window.location.pathname将为您提供目录以及页面名称。然后,您可以使用.substring()来获取目录:

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

希望这有帮助!

答案 1 :(得分:20)

您可以使用window.location.pathname.split('/');

这将产生一个包含/'s

之间所有项目的数组

答案 2 :(得分:10)

如果你不是在谈论URL字符串,这将适用于文件系统上的实际路径。

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

答案 3 :(得分:9)

对于/和\:

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

要返回没有尾部斜杠,请执行:

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

答案 4 :(得分:8)

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

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

答案 5 :(得分:5)

如果您想要完整的网址,例如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);

如果您最后不需要斜杠,请在+1后删除location.lastIndexOf("/")+1

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

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

答案 6 :(得分:5)

这个单线作品:

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

答案 7 :(得分:3)

假设您正在谈论当前网址,您可以使用window.location解析部分网址。 请参阅:http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript

答案 8 :(得分:1)

window.location。路径名

答案 9 :(得分:1)

如果您需要完整的网址,例如website.com/workingdirectory/使用: window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, '');

答案 10 :(得分:1)

获取当前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;
}