将网址转化为map或对象,方便取值

1. URL

function getQuerySearchParams(key) {
    var urlObj = new URL(location.href);
    return urlObj.searchParams.get(key);
}

2. URLSearchParams

function getQuerySearchParams(key) {
    var urlObj = new URL(location.href);
    console.log(urlObj.searchParams instanceof URLSearchParams) // true
    return urlObj.searchParams.get(key);
}

3. reduce

const URL_SEARCH ='?source=baidupc_utmId_5100&plan=A005-qglrgmc&unit=a010-mp4&keyword=mp4zgif&keywordid=20210343653&bd_vid=7019318071742353099'
var urlObj = URL_SEARCH.slice(1) // 去掉第一个?号字符
.split('&')
.filter(Boolean)
.reduce((cur, val)=> {
    const idx = val.indexOf('=') // 获取第一个=号所在的下标
    cur[(val.substring(0, idx))] = encodeURIComponent(val.substring(idx+1));

    return cur;
}, {})
const getQuerySearchParams = (key) => urlObj[key]
console.log(getQuerySearchParams('unit'))

4. 正则

注意\w没有包含所有的字符, 发现比较特殊的添加一下并仔细验证一下!!!

var url ='?source=baidupc_utmId_5100&plan=A005-qglrgmc&unit=a010-mp4&keyword=mp4zgif&keywordid=20210343653&bd_vid=7019318071742353099'
function getQuerySearchParams(key) {
    var obj = {};
    url.replace(/\??([\w-]+)=([\w-]+)&?/g, function(_, matchKey, matchValue) {
       if (!obj[matchKey]) {
        obj[matchKey] = matchValue;
       } else {
           var temp = obj[matchKey];
           obj[matchKey] = [].concat(temp, matchValue);
       }
    });
    if (!key) {
        return obj;
    } else {
        for (let ele in obj) {
            if (ele = key) {
                return obj[ele];
            }
        }
        return '';
    }
}
console.log(getQuerySearchParams('unit'))

你可能感兴趣的:(算法,JavaScript面试问题,正则,javascript,前端)