从路径中提取 URL 的目录,不带文件名,例如“index.html”

Extract URL's directory from path, without file name such as "index.html"

本文关键字:例如 文件名 index html 提取 URL 路径      更新时间:2023-09-26

我正在寻找纯JavaScript代码(没有jQuery等)来学习当前加载页面URL的目录路径组件。

例如,如果我的页面加载为"http://localhost/myapp/index.html",我喜欢以"http://localhost/myapp/"结尾。

我需要这个才能在同一位置创建不同文件的路径,例如"http://localhost/myapp/other.html"。

看起来这个技巧可以做到:

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

这是一种安全的方法,还是更复杂的 URL 会失败?

突出显示问题中对我有帮助的评论:

系统发育的评论:

简单的解决方案是location.href.replace(/[^/]*$/,''); then。

还有一个需要考虑的选项,它的好处是任何查询字符串都不会成为问题,因为 window.location.pathname 不会选取查询字符串。

window.location.origin + window.location.pathname.slice(0, window.location.pathname.lastIndexOf('/'))

更好的解决方案是

location.href.replace(/'/[^'/]+?'.[^'/]+?$/, '/')