How to convert URL parameters to a JavaScript object?

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

    Another solution based on the latest standard of URLSearchParams (https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

    function getQueryParamsObject() {
      const searchParams = new URLSearchParams(location.search.slice(1));
      return searchParams
        ? _.fromPairs(Array.from(searchParams.entries()))
        : {};
    }
    

    Please note that this solution is making use of

    Array.from (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

    and _.fromPairs (https://lodash.com/docs#fromPairs) of lodash for the sake of simplicity.

    It should be easy to create a more compatible solution since you have access to searchParams.entries() iterator.

提交回复
热议问题