How to convert URL parameters to a JavaScript object?

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

    2019 One-Liner Approach

    For your specific case:

    Object.fromEntries(new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5'));
    

    For the more generic case where someone wants to parse query params to an object:

    Object.fromEntries(new URLSearchParams(location.search));
    

    If you're unable to use Object.fromEntries, this will also work:

    Array.from(new URLSearchParams(window.location.search)).reduce((o, i) => ({ ...o, [i[0]]: i[1] }), {});
    

提交回复
热议问题