【js基础】之BOM操作

 阅读约 5 分钟

1.知识点

  • navigator (navigator.userAgent)
  • screen (screen.width / screen.heigght)
  • location
  • history (history.back() / history.forward())
//示例
https://segmentfault.com/search?q=web#mid=100

//整个url
location.href
"https://segmentfault.com/search?q=web#mid=100"

//协议
location.protocol
"https:"

//域名
location.host
"segmentfault.com"

//路径
location.pathname
"/search"

//参数
location.search
"?q=web"

//哈希
location.hash
"#mid=100"

2.检验浏览器的类型

navigator.userAgent

var ua = navigator.userAgent;
var isChrome = ua.indexOf('Chrome');
console.log(isChrome );

3.解析url

  1. 手动解析
function getQueryStringArgs(url){
        url = url == null ? window.location.href : url;
        var qs = url.substring(url.lastIndexOf("?") + 1);
        var args = {};
        var items = qs.length > 0 ? qs.split('&') : [];
        var item = null;
        var name = null;
        var value = null;
        for(var i=0; i<items.length; i++){
            item = items[i].split("=");
            //用decodeURIComponent()分别解码name 和value(因为查询字符串应该是被编码过的)。
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);

            if(name.length){
                args[name] = value;
            }
        }

        return args;
    }
console.log(getQueryStringArgs('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
    // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火车票网上订票官网"}
  1. 使用正则
function getQueryObject(url) {
        url = url == null ? window.location.href : url;
        var search = url.substring(url.lastIndexOf("?") + 1);
        var obj = {};
        var reg = /([^?&=]+)=([^?&=]*)/g;
        // [^?&=]+表示:除了?、&、=之外的一到多个字符
        // [^?&=]*表示:除了?、&、=之外的0到多个字符(任意多个)
        search.replace(reg, function (rs, $1, $2) {
            var name = decodeURIComponent($1);
            var val = decodeURIComponent($2);
            val = String(val);
            obj[name] = val;
            return rs;
        });
        return obj;
    }
    console.log(getQueryObject('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
    // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火车票网上订票官网"}
阅读 370发布于 2018-09-07
推荐阅读

前端知识体系梳理

7 人关注
24 篇文章
专栏主页
目录