How to convert URL parameters to a JavaScript object?

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

    Using phpjs

    function parse_str(str, array) {
      //       discuss at: http://phpjs.org/functions/parse_str/
      //      original by: Cagri Ekin
      //      improved by: Michael White (http://getsprink.com)
      //      improved by: Jack
      //      improved by: Brett Zamir (http://brett-zamir.me)
      //      bugfixed by: Onno Marsman
      //      bugfixed by: Brett Zamir (http://brett-zamir.me)
      //      bugfixed by: stag019
      //      bugfixed by: Brett Zamir (http://brett-zamir.me)
      //      bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
      // reimplemented by: stag019
      //         input by: Dreamer
      //         input by: Zaide (http://zaidesthings.com/)
      //         input by: David Pesta (http://davidpesta.com/)
      //         input by: jeicquest
      //             note: When no argument is specified, will put variables in global scope.
      //             note: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
      //             test: skip
      //        example 1: var arr = {};
      //        example 1: parse_str('first=foo&second=bar', arr);
      //        example 1: $result = arr
      //        returns 1: { first: 'foo', second: 'bar' }
      //        example 2: var arr = {};
      //        example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
      //        example 2: $result = arr
      //        returns 2: { str_a: "Jack and Jill didn't see the well." }
      //        example 3: var abc = {3:'a'};
      //        example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
      //        returns 3: {"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}
    
      var strArr = String(str)
        .replace(/^&/, '')
        .replace(/&$/, '')
        .split('&'),
        sal = strArr.length,
        i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
        postLeftBracketPos, keys, keysLen,
        fixStr = function(str) {
          return decodeURIComponent(str.replace(/\+/g, '%20'));
        };
    
      if (!array) {
        array = this.window;
      }
    
      for (i = 0; i < sal; i++) {
        tmp = strArr[i].split('=');
        key = fixStr(tmp[0]);
        value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
    
        while (key.charAt(0) === ' ') {
          key = key.slice(1);
        }
        if (key.indexOf('\x00') > -1) {
          key = key.slice(0, key.indexOf('\x00'));
        }
        if (key && key.charAt(0) !== '[') {
          keys = [];
          postLeftBracketPos = 0;
          for (j = 0; j < key.length; j++) {
            if (key.charAt(j) === '[' && !postLeftBracketPos) {
              postLeftBracketPos = j + 1;
            } else if (key.charAt(j) === ']') {
              if (postLeftBracketPos) {
                if (!keys.length) {
                  keys.push(key.slice(0, postLeftBracketPos - 1));
                }
                keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
                postLeftBracketPos = 0;
                if (key.charAt(j + 1) !== '[') {
                  break;
                }
              }
            }
          }
          if (!keys.length) {
            keys = [key];
          }
          for (j = 0; j < keys[0].length; j++) {
            chr = keys[0].charAt(j);
            if (chr === ' ' || chr === '.' || chr === '[') {
              keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
            }
            if (chr === '[') {
              break;
            }
          }
    
          obj = array;
          for (j = 0, keysLen = keys.length; j < keysLen; j++) {
            key = keys[j].replace(/^['"]/, '')
              .replace(/['"]$/, '');
            lastIter = j !== keys.length - 1;
            lastObj = obj;
            if ((key !== '' && key !== ' ') || j === 0) {
              if (obj[key] === undef) {
                obj[key] = {};
              }
              obj = obj[key];
            } else { // To insert new dimension
              ct = -1;
              for (p in obj) {
                if (obj.hasOwnProperty(p)) {
                  if (+p > ct && p.match(/^\d+$/g)) {
                    ct = +p;
                  }
                }
              }
              key = ct + 1;
            }
          }
          lastObj[key] = value;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 14:31

    A concise solution:

    location.search
      .slice(1)
      .split('&')
      .map(p => p.split('='))
      .reduce((obj, pair) => {
        const [key, value] = pair.map(decodeURIComponent);
        obj[key] = value;
        return obj;
      }, {});
    
    0 讨论(0)
  • 2020-11-22 14:33
    //under ES6 
    const getUrlParamAsObject = (url = window.location.href) => {
        let searchParams = url.split('?')[1];
        const result = {};
        //in case the queryString is empty
        if (searchParams!==undefined) {
            const paramParts = searchParams.split('&');
            for(let part of paramParts) {
                let paramValuePair = part.split('=');
                //exclude the case when the param has no value
                if(paramValuePair.length===2) {
                    result[paramValuePair[0]] = decodeURIComponent(paramValuePair[1]);
                }
            }
    
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 14:34

    ES6 one liner (if we can call it that way seeing the long line)

    [...new URLSearchParams(location.search).entries()].reduce((prev, [key,val]) => {prev[key] = val; return prev}, {})

    0 讨论(0)
  • 2020-11-22 14:35

    One of the simplest way to do this using URLSearchParam interface.

    Below is the working code snippet:

    let paramObj={},
        querystring=window.location.search,
        searchParams = new URLSearchParams(querystring);    
    
      //*** :loop to add key and values to the param object.
     searchParams.forEach(function(value, key) {
          paramObj[key] = value;
       });
    
    0 讨论(0)
  • 2020-11-22 14:36

    There's a lightweight library called YouAreI.js that's tested and makes this really easy.

    YouAreI = require('YouAreI')
    uri = new YouAreI('http://user:pass@www.example.com:3000/a/b/c?d=dad&e=1&f=12.3#fragment');
    
    uri.query_get() => { d: 'dad', e: '1', f: '12.3' }
    
    0 讨论(0)
提交回复
热议问题