How to convert URL parameters to a JavaScript object?

前端 未结 30 1371
时光取名叫无心
时光取名叫无心 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:20

    Here's my quick and dirty version, basically its splitting up the URL parameters separated by '&' into array elements, and then iterates over that array adding key/value pairs separated by '=' into an object. I'm using decodeURIComponent() to translate the encoded characters to their normal string equivalents (so %20 becomes a space, %26 becomes '&', etc):

    function deparam(paramStr) {
        let paramArr = paramStr.split('&');     
        let paramObj = {};
        paramArr.forEach(e=>{
            let param = e.split('=');
            paramObj[param[0]] = decodeURIComponent(param[1]);
        });
        return paramObj;
    }
    

    example:

    deparam('abc=foo&def=%5Basf%5D&xyz=5')
    

    returns

    {
        abc: "foo"
        def:"[asf]"
        xyz :"5"
    }
    

    The only issue is that xyz is a string and not a number (due to using decodeURIComponent()), but beyond that its not a bad starting point.

提交回复
热议问题