Clean and simple Underscore one liner for parsing URL parameters
November 14, 2013
Underscore methods can be combined in lots of cool ways to perform complicated transformations in just a few elegant steps. Here’s a short javascript and underscore one liner for transforming URL parameters from the location.search property into an object:
Javascript:
Coffeescript:
It will turn a string like this:
Into an object like this:
The one liner is hard to read, but _.chain allows us to chain the nested calls for readability:
Javascript:
Coffeescript:
There are many ways to parse url parameters, but by using underscore the code is clean and succinct. It will also clean up poorly formed url parameters like ?&post=2&&category&language=&.
If you need to do extensive url manipulation I recommend using a dedicated library, but this should be handy if you just need to parse the search field once.