[Laszlo-dev] Re: [Dev] javascript routine for converting CGI query string into key-value array?

Max Carlson max at laszlosystems.com
Thu Jan 27 23:37:33 PST 2005


Oliver Steele wrote:
> [Moved to laszlo-dev:]
> 
> On Jan 27, 2005, at 10:52 PM, Henry Minsky wrote:
> 
>> Does anyone have an efficient routine for converting a query string
>> into a key-value javascript object?
>>
>> I.e.,
>>
>> parseQueryString("color=red&foo=Hello+World!&bar=%2fxyz")
>> would return
>> {color: 'red', foo: "Hello World!", bar: "/xyz"}
> 
> 
> It's not particularly efficient, but I don't know anything better than 
> this (untested):
> function parseQueryString(query)
>   var parameters = query.split('&');
>   var queries = {};
>   for (var i in parameters) {
>     var key = parameters[i];
>     var value = '';
>     var n = key.indexOf('=');
>     if (n > 0) {
>       value = unquoteQueryValue(key.substring(n+1));
>       key = key.substring(0, n);
>     }
>     queries[key] = value;
>   }
>   return queries;
> }
> function unquoteQueryValue(s) {
>   if (s.indexOf('%') < 0) return s; // fast path
>   var spans = s.split('%');
>   var accum; // initialized first time through
>   for (var i in spans) {
>     var span = spans[i];
>     if (i == 0) {
>       accum = span;
>     } else {
>       accum += String.fromCharCode(parseInt(span.substring(0, 2), 16));
>       accum += span.substring(2);
>     }
>   }
>   return accum;
> }
> 
> but it's worth looking to see whether there's a Flash API for 
> unquoteQueryValue(), both for speed and because my version isn't tested 
> or finished (it doesn't check for malformed content such as '%%%', or 
> '%3' at the end of a string).

unescape() should be faster since it's likely native.  It might make 
sense to add the above parseQueryString() method as a parse() method in 
the LzParam object.  You could use LzParam's delimiter and separator 
values which default to & and = respectively.  It would be nice to have 
the constructor take a query string and optional delimiter and separator 
arguments to make parsing more convenient, e.g:

var q = new LzParam('foo=bar&bla=blarg');

or

var q = new LzParam('foo+bar-bla+blarg', '-', '+');

would parse the string with the specified or default delimiter and 
separator.

See:

http://www.laszlosystems.com/lps-2.2/docs/reference/lzparam.html

-Max


More information about the Laszlo-dev mailing list