How to convert URL parameters to a JavaScript object?

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

    There is no native solution that I'm aware of. Dojo has a built-in unserialization method if you use that framework by chance.

    Otherwise you can implement it yourself rather simply:

    function unserialize(str) {
      str = decodeURIComponent(str);
      var chunks = str.split('&'),
          obj = {};
      for(var c=0; c < chunks.length; c++) {
        var split = chunks[c].split('=', 2);
        obj[split[0]] = split[1];
      }
      return obj;
    }
    

    edit: added decodeURIComponent()

提交回复
热议问题