URLVariables Replacement

Actionscript:
  1. function decode(str:String):Object {
  2.     var vars:Object={};
  3.     var parse:Array =str.split("&");
  4.     var i:int=0;
  5.     for (i = 0; i<parse.length; i++) {
  6.         var pair:Array=parse[i].split("=");
  7.         if (pair.length==2) {
  8.             vars[pair[0]]=pair[1];
  9.         }
  10.     }
  11.     return vars;
  12. }
  13.  
  14. var nameValuePairs="one=1&&two=éllo&three=1000&four=0xFF0000";
  15. var parsed:Object=decode(nameValuePairs);
  16.  
  17. trace(parsed.one);
  18. trace(parsed.two);
  19. trace(parsed.three);
  20. trace(parsed.four);
  21.  
  22. /*outputs:
  23. 1
  24. éllo
  25. 1000
  26. 0xFF0000
  27. */

Well not exactly a URLVariables replacement, but I often use the URLVariables.decode() function and find that its very picky... like if there is an extra & or something it freaks out and breaks, or if there are line returns. As a quick and simple solution the other day I wrote this function into part of a class (Model class) that I was working on. Fixed the problem and even handles Spanish characters nicely.

There is plenty of room for improvement with this simple function... feel free to post improvements in the comments.

This entry was posted in external data, string manipulation, strings and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted March 8, 2010 at 3:47 pm | Permalink

    Some time ago i wrote replacement for URLVariables to add support of objects and arrays. As you may know, PHP can accept arrays from URL:
    ?array[0]=1&array[1]=2&array=3
    Here is posting about this class:
    http://translate.google.com/translate?hl=ru&sl=ru&tl=en&u=http%3A%2F%2Factualwave.com%2Fblog%2F%3Fp%3D91

  2. Posted March 8, 2010 at 6:52 pm | Permalink

    very nice a_[w]

One Trackback

  1. [...] URLVariables Replacement [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*