如何在JavaScript中获取当前URL的目录部分? [英] How to get the directory part of current URL in JavaScript?

查看:134
本文介绍了如何在JavaScript中获取当前URL的目录部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在网页顶部添加一个返回目录按钮,该按钮将重定向到同一个URL,但没有文件名。

I'm trying to add a "back to dir" button at the top of a web page, which would redirect the user to the same URL, but with no filename in it.

例如,在查看URL时单击该按钮

For example, clicking that button while viewing the URL

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

将重定向到

http://example.com/somedir/

所以我创建了以下代码:

So I've created the following code:

<html>
<body>

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

</body>
</html>

但是我错过了正确的代码,它会从 document.URL

but I'm missing the correct code, which would shave away the filename from the current URL in document.URL

有人有个好主意吗?

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

Here is the JSFiddle link: http://jsfiddle.net/afarber/PERBY/

我不想一次使用jQuery。

And I'd prefer not to use jQuery this one time.

推荐答案

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

它将工作肯定!

这篇关于如何在JavaScript中获取当前URL的目录部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆