使用Javascript从我的windows URL获取基本URL和文件路径

使用Javascript从我的windows URL获取基本URL和文件路径,javascript,html,Javascript,Html,嗨,我试图从我的windows URL获取基本URL和文件路径。但是我无法获取。请更正我 URL是: var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/"; 当前输出为: ? 所需输出为: 使用的代码: var baseURL = location.proto

嗨,我试图从我的windows URL获取基本URL和文件路径。但是我无法获取。请更正我

URL是:

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";

当前输出为: ?

所需输出为:

使用的代码:

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";

添加location.pathname,使其成为

var baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + location.pathname;
另外,为什么不简单地使用location.href来获取整个内容呢


上有很好的参考,可能是这样的:

var sBase = location.href.substr(0, location.href.lastIndexOf("/") + 1);

从您使用的代码中可以看出,当前输出不可能以“index.jsp”结尾。更安全的方法是使用base标记(请参阅)并使用document.querySelector('head>base').getAttribute('href')进入js。这是我问题的完美答案。。谢谢。这实际上不是一个好方法,因为它在以例如
“/foo/bar/baz.html?next=/login”
结尾的url上失败。最好手动重建URL以确保不包含查询和片段。解决@StefanArentz的问题,它将变成
location.origin+location.pathname.substr(0,location.pathname.lastIndexOf(“/”)+1)