Using Underscore.js to get URL parameters

This is a neat little function I built using Underscore (and some common javascript functions) to get all the parameters in a url, and return them as an object.  I’ll go through the function line by line…

function getParams() {
  // gets url parameters and builds an object
  return _.chain(location.search.slice(1).split('&'))
         .map(function (item) { if (item) { return item.split('='); } })
         .compact()
         .object()
         .value();
}

_.chain() returns a wrapped object that allows us to continue modifying results with other underscore methods.  You then add .value() at the end of the chain to return the end result.

location.search returns the querystring part of a URL.  For example, if the current URL is http://www.aliwright.co.uk/contact.php?email=someone@example.com&subject=hello and you used this line of code:

var x = location.search;

The result of x will be:

?email=someone@example.com&subject=hello

slice(1) returns the string from the starting point of 1.  Seeing as it counts from zero, this returns the url string without the question mark at the start:

email=someone@example.com&subject=hello

split('&') splits the string into an array like so:

['email=someone@example.com', 'subject=hello']

.map() produces a new array of values by mapping each value in list through a transformation function.  The function inside splits each array value using the = symbol.  So in effect it creates a new array like so:

[['email','someone@example.com'], ['subject','hello']]

.compact() returns a copy of the array with all falsy values removed.  Think of it as a spot of tidying up…

.object() converts the array into an object, like so:

{
  email: 'someone@example.com',
  subject: 'hello'
}

And as explained above, value() simply breaks out of the chain and returns the object.  Obviously there’s a glaring omission – what about hash tags?  Well this wasn’t an issue when I’ve needed this function as I didn’t need the hash tag value returned, but if one exists in the url this would cause an incorrect value to be returned.  You could probably do something simple by doing a string replace using the location.hash value.

As you can imagine, doing something similar in pure javascript would involve far more code, be harder to read, and use more memory.  I hope this helps others out, and also demonstrates how wonderful Underscore is!

See my Underscore/JS function in JSFiddle

I’ve had to tweak it a little to simulate url parameters, but you get the idea…

Share my post!
Facebooktwitterredditpinterestlinkedinmail Loading Likes...