取字符串的三个函数:slice(start,[end]),substring(start,[end])和substr(start,[length])
常用的路径获取方式如下:
http://localhost:8020/a/b/c.html
window.location.pathname.substring(1, window.location.pathname.substring(1).indexOf('/')) :获取 a
window.location.pathname:设置或获取对象指定的“文件名”或路径。/a/b/c.html
window.location.href:设置或获取整个 URL 为字符串。http://localhost:8020/a/b/c.html
window.location.port:设置或获取与 URL 关联的端口号码。8020
window.location.protocol:设置或获取 URL 的协议部分。http:
window.location.hash:设置或获取 href 属性中在井号“#”后面的分段。参数
window.location.host:设置或获取 location 或 URL 的 hostname 和 port 号码。127.1.1.1:8020
window.location.search:设置或获取 href 属性中跟在问号及其后面的部分(包含问号)。
function getRootPath() {
var curPath = window.location.href;
//获取主机地址之后的目录,如: /a/b/c.html
var pathName = window.location.pathname;
// a/b/c.html
var a = pathName.substring(1);
var b = a.indexOf('/');
// a
var c = pathName.substring(1, b + 1);
var d = curPath.indexOf(pathName);
var pos = d + 1 + b;
//http://127.0.0.1:8020/a
var url = window.location.href.substring(0, pos);
return url;
}