How to convert URL parameters to a JavaScript object?

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

    Split on & to get name/value pairs, then split each pair on =. Here's an example:

    var str = "abc=foo&def=%5Basf%5D&xy%5Bz=5"
    var obj = str.split("&").reduce(function(prev, curr, i, arr) {
        var p = curr.split("=");
        prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
        return prev;
    }, {});
    

    Another approach, using regular expressions:

    var obj = {}; 
    str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
        obj[decodeURIComponent(key)] = decodeURIComponent(value);
    }); 
    

    This is adapted from John Resig's "Search and Don’t Replace".

提交回复
热议问题