URL parameters in Javascript

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.

  2. function get_url_params(){
  3. var _GET = {};
  4. var s = location.search.replace( /^\?|#.*$/g, '' );
  5. if( s ) {
  6. var qsParts = s.split('&');
  7. var i, nv;
  8. for (i = 0; i < qsParts.length; i++) {
  9. var nv = qsParts[i].split('=');
  10. var n=decodeURIComponent(nv[0]);
  11. var v=decodeURIComponent(nv[1]);
  12. var k=n.split(/[\[\]\.]/);
  13. if(k.length){
  14. if(_GET[k[0]])_GET[k[0]][k[1]]=v;
  15. else {
  16. if(parseInt(k[1])==k[1])
  17. _GET[k[0]]=[];
  18. else _GET[k[0]]={};
  19. _GET[k[0]][k[1]]=v;
  20. }
  21. }else _GET[n] = v;
  22. }
  23. }
  24. return _GET;
  25. }

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.

One thought on “URL parameters in Javascript

  1. 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!

Leave a Reply