我正在寻找纯JavaScript代码(不使用jQuery等库)来了解当前加载页面的URL的目录路径组件。
例如,如果我的页面被加载为“http://localhost/myapp/index.html”,我希望最终得到“http://localhost/myapp/”。
我需要这个来创建相同位置不同文件的路径,例如“http://localhost/myapp/other.html”。
我正在寻找纯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,它是否会失败?
localhost/client/build
是怎么样的?它会变成localhost/client
,这可能不是您想要的。 - charlag还有一个值得考虑的选项,它的好处是任何查询字符串都不会成为问题,因为window.location.pathname不会获取查询字符串。
window.location.origin + window.location.pathname.slice(0, window.location.pathname.lastIndexOf('/'))
location.href.replace(/\/[^\/]+?\.[^\/]+?$/, '/')
location.href.replace(/[^/]*$/, '');
。 - Phylogenesis