How to convert URL parameters to a JavaScript object?

前端 未结 30 1396
时光取名叫无心
时光取名叫无心 2020-11-22 13:57

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5

How can I convert it into a JavaScript object like this?

{
          


        
30条回答
  •  深忆病人
    2020-11-22 14:33

    //under ES6 
    const getUrlParamAsObject = (url = window.location.href) => {
        let searchParams = url.split('?')[1];
        const result = {};
        //in case the queryString is empty
        if (searchParams!==undefined) {
            const paramParts = searchParams.split('&');
            for(let part of paramParts) {
                let paramValuePair = part.split('=');
                //exclude the case when the param has no value
                if(paramValuePair.length===2) {
                    result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
                }
            }
    
        }
        return result;
    }
    

提交回复
热议问题