Tips_url 字符串解析为 Object

一. javascript 实现一个函数 parseUrl(url),将一段 url 字符串解析为 Object.

eg:

parseUrl("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");

返回结果

{
    protocol: "http",
    host: "www.xiyanghui.com",
    path: "/product/list",
    query: {
        id: "123456",
        sort: "discount"
    },
    hash: "title"
}

  

 /**
     * 
     * @param {*} search a.search
     */
    function parseParams(search) {
        var ret = {};
        var searchArr = [];
        searchArr = search.replace(/^\?/, '').split('&');
        for (let i = 0; i < searchArr.length; i++) {
            if (searchArr[i]) {
                let querys = searchArr[i].split('=');
                console.log(querys);
                ret[querys[0]] = querys[1];
            }
        }
        return ret;
    }
    /**
     * 通过创建a标签
     * @param {*} url 
     */
    function parseUrl(url) {
        var a = document.createElement('a');
        a.href = url;
        return ({
            protocol: a.protocol,
            hostname: a.hostname,
            port: a.port,
            search: a.search,
            params: parseParams(a.search),
            hash: a.hash.replace('#', ''),
            path: a.pathname,
        })
    }
    var rest = parseUrl("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");
    console.log(rest);
    /**
     * 通过new URL
     * @param {*} url 
     */
    // IE12及以上兼容
    function parseUrlBynewUrl(url) {
        var url = new URL(url);
        return ({
            protocol: url.protocol,
            hostname: url.hostname,
            port: url.port,
            search: url.search,
            params: parseParams(url.search),
            hash: url.hash.replace('#', ''),
            path: url.pathname,
        })
    }
    var restt = parseUrlBynewUrl("http://www.xiyanghui.com/product/list?id=123456&sort=discount#title");
    console.log(restt);
}

 

posted @ 2019-07-02 09:55  忍冬。  阅读(410)  评论(0编辑  收藏  举报