Make a JavaScript array from URL

前端 未结 4 2061
甜味超标
甜味超标 2020-12-05 02:35

I need to make a Javascript array from URL, eg:

turn this:

http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x45         


        
4条回答
  •  长情又很酷
    2020-12-05 03:20

    the above function URLToArray is not working when url string has elem[]=23&elem[]=56.. see below the adapted function... hope it is working - not 100% tested

    function URLToArray(url) {
            var request = {};
            var arr = [];
            var pairs = url.substring(url.indexOf('?') + 1).split('&');
            for (var i = 0; i < pairs.length; i++) {
              var pair = pairs[i].split('=');
    
              //check we have an array here - add array numeric indexes so the key elem[] is not identical.
              if(endsWith(decodeURIComponent(pair[0]), '[]') ) {
                  var arrName = decodeURIComponent(pair[0]).substring(0, decodeURIComponent(pair[0]).length - 2);
                  if(!(arrName in arr)) {
                      arr.push(arrName);
                      arr[arrName] = [];
                  }
    
                  arr[arrName].push(decodeURIComponent(pair[1]));
                  request[arrName] = arr[arrName];
              } else {
                request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
              }
            }
            return request;
        }
    

    where endWith is taken from here

    function endsWith(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
    }
    

提交回复
热议问题