21.url参数取出

 let url = 'https://www.suning.com/?source=hao123&medium=mingzhan#abcs'
        let askIndex = url.indexOf('?');
        let wellIndex = url.indexOf('#');
        // 从问号索引位置截取得到 井号 索引位置 不包含井号
        let askText = url.substring(askIndex + 1, wellIndex);
        // 截取井号 后面的
        let wellText = url.substring(wellIndex + 1);
        // 2.问号后面值详细处理
        let askAry = askText.split("&")
        let res = {};
        askAry.forEach((item, index) => {
            // item: 当前数组中循环这一项
            // 以等号分割
            let n = item.split('=')
            // 属性名为 数组的第一项,属性值为第二项
            res[n[0]] = n[1];
        });
        res['HASH'] = wellText
        console.log(res);

        // 优化封装 取出url参数
        function queryUrlParams(url) {
            let askIn = url.indexOf('?'),
                wellIn = url.indexOf('#'),
                askText = '',
                wellText = '';
            wellIn === -1 ? wellIn = url.length : null;
            // 如果问号存在,从问号所引处截取 到井号结束
            askIn > 0 ? askText = url.substring(askIn + 1, wellIn) : null;
            // 井号内容
            wellText = url.substring(wellIn + 1);
            // 2.获取每一部分信息
            let res = {};
            wellText !== "" ? res['HASH'] = wellText : null;
            if (askText !== '') {
                let ary = askText.split('&');
                ary.forEach(item => {
                    let itemAry = item.split('=');
                    res[itemAry[0]] = itemAry[1];
                })
            }
            return res;
        }
        let url = "https://www.suning.com/?source=hao123&medium=mingzhan#abcs"
        let news = queryUrlParams(url)
        console.log(news);
     // ======================== 正则封装
    function queryUrlParams(url) {
    let res = {},
        reg1 = /([^?=&#]+)=([^?=&#]+)/g,
        reg2 = /#([^?=&#]+)/g;
    url.replace(reg1, (n, x, y) => res[x] = y);
    url.replace(reg2, (n, x) => res['HASH'] = x);
    return res;
    }
    let url = "https://www.suning.com/?source=hao123&medium=mingzhan#abcs"
    let news = queryUrlParams(url)
    console.log(news);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端酱紫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值