js解析复杂url参数(兼容hash和search)

2021-05-25 | 2,899浏览 | 0评论 | 标签:js获取复杂url参数

如果你想从复杂的url中获取参数,可以试试这个方法:(分别对hash和search参数进行处理)

const queryParams = (href = window.location.href, needDecode = true) => {
    const reg = /([^&=]+)=([\w\W]*?)(&|$|#)/g
    const { search, hash } = new URL(href);
    const args = [search, hash];
    let obj = {};
    for (let i = 0; i < args.length; i++) {
        const str = args[i];
        if (str) {
            const s = str.replace(/#|\//g, '')
            const arr = s.split('?')
            if (arr.length > 1) {
                for (let i = 1; i < arr.length; i++) {
                    let res;
                    while ((res = reg.exec(arr[i]))) {
                        obj[res[1]] = needDecode ? decodeURIComponent(res[2]) : res[2]
                    }
                }
            }
        }
    }
    return obj;
}


//eg.

queryParams('https://denghao.me?a=1');               // => {a:1}
queryParams('https://denghao.me/#/detail?a=1');      // => {a:1}
queryParams('https://denghao.me/?a=1#/detail');      // => {a:1}
queryParams('https://denghao.me/?a=1#/detail?b=2');  // => {a:1,b:2}
(本篇完。有疑问欢迎留言探讨)

留言:

*

* (方便回复通知)

打赏
编辑代码 运行结果
退出