问号传参解析(queryURLParam)(持续更新)

Solution 2

function queryURLParams(url) {
    // 1.获取 ?和 # 之后的文本
    let askIdx = url.indexOf('?'),
        wellIdx = url.indexOf('#'),
        askText = '',
        wellText = '';
    wellIdx === -1 ? wellIdx = url.length : null;
    wellText = url.substring(wellIdx + 1);
    if (askIdx > -1 ) {
        askText = url.substring(askIdx + 1, wellIdx)
    }
    // 2.获取的文本进行解析。拼成一个对象返回
    let obj = {};
    wellText.length > 0 ? obj['HASH'] = wellText : null;
    if (askText) {
        askText.split('&').forEach(item => {
            let arr = item.split('='),
                key = arr[0],
                val = arr[1];
            obj[key] = val;
        })
    }
    return obj;
}

Solution 2

function queryURLParams(url) {
    // 创建a标签(A元素)来获取问号参数和哈希值
    let link = document.createElement('a');
    link.href = url; // 面向对象
    let askText = link.search.substr(1), // 拿到的是‘?xxxx’
        wellText = link.hash.substr(1), //拿到的是‘#xxxx’
        obj = {};
    // 向对象中进行存储
    wellText ? obj['HASH'] = wellText : null;
    if (askText) {
        let arr = askText.split(/(?:&|=)/g);
        for (let i = 0; i < arr.length; i += 2) {
            obj[arr[i]] = arr[i + 1];
        }
    }
    return obj;
}

Solution 3(正则)

测试用例

// case 1: ? #
let result = queryURLParams('https://sports.qq.com/kbsweb/game.htm?lx=1&name=ty#55055776');
console.log(result);
// case 2: #
let result2 = queryURLParams('https://sports.qq.com/kbsweb/game.htm#55055777');
console.log(result2);
// case 3: ?
let result3 = queryURLParams('https://sports.qq.com/kbsweb/game.htm?lx=1&name=ty');

console.log(result3);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值