I wanted a piece of code in pure javascript ( no framework required ) that could extract the parameters in the query string part of an URL.
I wanted it to be able to extract the parameters in this format name[key]=value like they are used in php applications.
I found a piece of code on some other blogs or forum posts but it didn't work as I expected so here is my take on this.
function get_url_params(){ var _GET = {}; var s = location.search.replace( /^\?|#.*$/g, '' ); if( s ) { var qsParts = s.split('&'); var i, nv; for (i = 0; i < qsParts.length; i++) { var nv = qsParts[i].split('='); var n=decodeURIComponent(nv[0]); var v=decodeURIComponent(nv[1]); var k=n.split(/[\[\]\.]/); if(k.length){ if(_GET[k[0]])_GET[k[0]][k[1]]=v; else { if(parseInt(k[1])==k[1]) _GET[k[0]]=[]; else _GET[k[0]]={}; _GET[k[0]][k[1]]=v; } }else _GET[n] = v; } } return _GET; }
This function one limitation: It doesn't work with multidimensional arrays. It's probably not hard to modify it to work like that but I only needed it to work with single dimension arrays.
First, this post looks odd. The avd image brakes the layout.
Then, as a best practice, you can extract qsParts.length or other array lenghts like this in a variable.
Also if/else should have {} even with one instruction.
But these are small things. The method is good!