How to convert URL parameters to a JavaScript object?

前端 未结 30 1555
时光取名叫无心
时光取名叫无心 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条回答
  •  猫巷女王i
    2020-11-22 14:41

    Edit

    This edit improves and explains the answer based on the comments.

    var search = location.search.substring(1);
    JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
    

    Example

    Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

    • decodeURI: abc=foo&def=[asf]&xyz=5
    • Escape quotes: same, as there are no quotes
    • Replace &: abc=foo","def=[asf]","xyz=5
    • Replace =: abc":"foo","def":"[asf]","xyz":"5
    • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}

    which is legal JSON.

    An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

    var search = location.search.substring(1);
    JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
    

    Example

    search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";
    

    gives

    Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
    

    Original answer

    A one-liner:

    JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')
    

提交回复
热议问题