zoukankan      html  css  js  c++  java
  • 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);
    }
    

     

  • 相关阅读:
    HashMap:JDK7 与 JDK8 的实现
    es简单介绍及使用注意事项
    mongo学习使用记录2 spring data
    mongo学习使用记录1
    数据库三范式
    mysql数据库中实现内连接、左连接、右连接
    JDK7与JDK8中HashMap的实现
    字符串按照相似度排序
    Linux shell 脚本小记2
    ReentrantLock源码了解
  • 原文地址:https://www.cnblogs.com/LinSL/p/11118697.html
Copyright © 2011-2022 走看看