如何在JavaScript中获取当前URL的目录部分?

18

我想在网页顶部添加一个“返回目录”按钮,点击后会将用户重定向至相同URL但没有文件名的地址。

例如,在查看以下URL时点击该按钮:

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

会将您重定向至

http://example.com/somedir/

因此,我已创建了以下代码:

<html>
<body>

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

</body>
</html>

但我缺少正确的代码,它可以从document.URL中削去当前URL的文件名。

有人有好的想法吗?

这是JSFiddle链接:http://jsfiddle.net/afarber/PERBY/

这一次,我宁愿不使用jQuery。

6个回答

32

尝试使用这个 document.URL.substr(0,document.URL.lastIndexOf('/'))

肯定会起作用的!


1
谢谢,这看起来很不错 - 甚至比我的正则表达式更好(我在那里打了一个错字...) - Alexander Farber
不用谢,如果它运行良好,请给它投票,以便其他人也可以从中受益。 - Abdul Rauf
6
如果当前的URL以斜杠结尾(通常情况下是这样),则此方法将无法起作用。 - Derek Henderson

4
这个一行代码也可以工作:
document.URL.split('/').slice(0, -1).join('/')

虽然这种方法可行,但比起@abdul-rauf发布的字符串解决方案要慢得多。 - frank-dspeed

4

console.log(new URL(document.URL));

你可以这样获取所有的对象:
{
  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"
}

最佳解决方案,不要使用hacky方法!您还可以从window.location访问这些参数和一些额外的参数,例如window.location.hostname - Reza Nooralizadeh

1
以下代码可获取目录,包括最后一个字符为斜杠的情况。
document.URL.replace(/\/[^/]+\/?$/, '');

这实际上表示以下内容(假设它们按此顺序找到):
1. \/:查找“/” 2. [^/]+:在其后查找一个或多个字符,这些字符不是“/” 3. \/?:在那些字符后面查找可选的“/” 4. $:查找字符串的结尾
然后通过''将它们删除,因此我们只剩下目录。
同样,这假定存在标记目录的斜杠,并且这不仅仅是URL,其中唯一的斜杠位于http://内。

1
我进行了修改,保留任何带有尾随斜杠的路径组件(因此已经是目录的URL保持不变):window.location.href.replace(/\/[^/]+$/, '/') - Robin Stewart

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

2
FYI:document.location已被弃用,请使用window.location - Teemu

0
尝试以下代码,它考虑了URL以斜杠结尾和不以斜杠结尾的情况:
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);

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