How to convert URL parameters to a JavaScript object?

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

    /**
     * Parses and builds Object of URL query string.
     * @param {string} query The URL query string.
     * @return {!Object}
     */
    function parseQueryString(query) {
      if (!query) {
        return {};
      }
      return (/^[?#]/.test(query) ? query.slice(1) : query)
          .split('&')
          .reduce((params, param) => {
            const item = param.split('=');
            const key = decodeURIComponent(item[0] || '');
            const value = decodeURIComponent(item[1] || '');
            if (key) {
              params[key] = value;
            }
            return params;
          }, {});
    }
    
    console.log(parseQueryString('?v=MFa9pvnVe0w&ku=user&from=89&aw=1'))
    see log

提交回复
热议问题