美文网首页让前端飞Web前端之路
获取 URL 中的 Query 参数

获取 URL 中的 Query 参数

作者: ares951753 | 来源:发表于2019-10-09 01:52 被阅读0次

需求描述

获取 URL 中的 Query 参数,例如:

https://www.example.com/test.html?a=param1&b=param2

代码片段

实现一

使用URLSearchParams对象,兼容性见Can I use

const urlString = 'https://www.example.com/test.html?a=param1&b=param2';
const urlObj = new URL(urlString);
const [a, b] = urlObj.searchParams.values();

实现二

function parseSearchParams(searchParamsString){
    return searchParamsString.split('&').reduce((searchParams, curKV)=>{
        const [k, v] = curKV.split('=').map(decodeURIComponent);
        searchParams[k] = v;

        return searchParams;
    }, {});
}

相关文章

网友评论

    本文标题:获取 URL 中的 Query 参数

    本文链接:https://www.haomeiwen.com/subject/jzqwpctx.html