window.location对象详解

以这个地址为例:https://www.baidu.com:80/?ie=UTF-8&wd=google


window.location.href
当前URL:https://www.baidu.com:80/s?ie=UTF-8&wd=google

window.location.protocol
协议:https

window.location.host
域名 + 端口:www.baidu.com:80

window.location.hostname
域名:www.baidu.com

window.location.port
端口:80

window.location.pathname
路径:/s

window.location.search
请求的参数:?ie=UTF-8&wd=google

有时候需要对搜索参数进行获取
function getQuery(name) {
  // 正则:[找寻'&' + 'url参数名字' = '值' + '&']('&'可以不存在)
    let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    let r = window.location.search.substr(1).match(reg);
    // substr(start,length)
    // substr() 的参数指定的是子串的开始位置和长度,因此它可以替代 substring() 和 slice() 来使用
    // ECMAscript 没有对该方法进行标准化,因此反对使用它。
    if(r != null) {
      // 对参数值进行解码
        return unescape(r[2]);
    }
    return null;
}

// 调用方法,注意需要传入String类型的数据,输出结果为String类型
getQuery('id');   // '123'




window.location.origin
'?'前边的URL:https://www.baidu.com/s


解决window.location.origin 的兼容问题
if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

原文地址:https://www.cnblogs.com/class1/p/12011743.html