定义一个方法获取一段携带参数的 url 中 key 对应的 value

196 阅读1分钟

思路

给定一段 url 地址,取出后面的参数转换成参数对象,然后再通过 key 找到对应的 value

方法一

let url = 'https://xxxx.com?a=1&b=2&c=&d'
function fn(url, key) {
    let arr = url.substr(url.indexOf('?')+1).split('&')
    let newObj = arr.reduce((obj, item)=>{
        obj[item.split('=')[0]] = item.split('=')[1]
        return obj
    }, {})
    return newObj[key]
}
        
console.log(fn(url, 'd')) // undefined

方法二

let url = 'https://xxxx.com?a=1&b=2&c=zs&d=李';
function p_urlParse(url, key) {
    let obj = {};
    let reg = /[?&][^?&]+=[^?&]+/g;
    let arr = url.match(reg);
    if (arr) {
        arr.forEach((item) => {
        let tempArr = item.substring(1).split('=');
        let key = decodeURIComponent(tempArr[0]);
        let val = decodeURIComponent(tempArr[1]);
        obj[key] = val;
        })
    }
    return obj[key];
};

console.log(p_urlParse(url, 'c')) // 'zs'