Tim Etler

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:

_.object(_.compact(_.map(location.search.slice(1).split('&'), function(item) {  if (item) return item.split('='); })));

Coffeescript:

_.object _.compact _.map location.search[1..].split('&'), (item) -> if item then item.split '='

It will turn a string like this:

"?post=2&category=programming&language=coffeescript"

Into an object like this:

{
    post: "2",
    category: "programming",
    language: "coffeescript"
}

The one liner is hard to read, but _.chain allows us to chain the nested calls for readability:

Javascript:

// Remove the '?' at the start of the string and split out each assignment
_.chain( location.search.slice(1).split('&') )
    // Split each array item into [key, value]
    // ignore empty string if search is empty
    .map(function(item) { if (item) return item.split('='); })
    // Remove undefined in the case the search is empty
    .compact()
    // Turn [key, value] arrays into object parameters
    .object()
    // Return the value of the chain operation
    .value();

Coffeescript:

#  Remove the '?' at the start of the string and split out each assignment
_.chain( location.search[1..].split('&') )
    #  Split each array item into [key, value]
    #  ignore empty string if search is empty
    .map( (item) -> if item then item.split('=') )
    #  Remove undefined in the case the search is empty
    .compact()
    #  Turn [key, value] arrays into object parameters
    .object()
    #  Return the value of the chain operation
    .value()

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.