Chronicling the trials and tribulations of developing for the modern web.



Parsing Parameters with Javascript

Posted by Pat Nakajima on November 19, 2007 in Programming.
Update: While this post is nice, a much better way to parse parameters is to use Prototype’s (if you’re using Prototype that is) built-in String#toQueryParams() method. To quote the official documentation, this method “Parses a URI-like query string and returns an object composed of parameter/value pairs.” Live and learn.

Wish you had a params object to use in your Javascript, just like the one you get in your Rails controllers? Well wish no longer. Just add the following script to your application code:
params = { };
document.URL.split('?')[1].split('&').each(function(par) {
  params[par.split('=')[0]] = par.split('=')[1];
})

Then when you’re on a page with a URL like “http://your-site.com/users?name=pat”, you can access the value of the name parameter like so: params['name'].

The biggest limitation of this script is that it’s limited to GET params, in other words, the ones found in the URL. Still, it’s a clean and easy way to get a Rails-like syntax in your Javascript.

commentsareclosed

Sorry, but comments are closed on this blog after 30 days.