Get URL parameters using JavaScript

This one will be quick and easy. I'm currently working on an Angular.js/MVC application and I need to grab the URL parameters from the current page. Simple right? Well not so much. Firstly, I'm not using ngRoute and, secondly, I don't want to use any other external library/utility. Just plain, old, vanilla JavaScript. How did I do it then?

Parsing URLs with JavaScript

I've created a simple method to manage this. The method is pretty straightforward. It takes a URL, parses the parameters with a bit of RegEx 'magic' and then returns an object with our parameters. Simple.

To use this on any page to grab the URL parameters you can just do this:

var urlToParse = location.search;
var result = parseQueryString(urlToParse );
console.info(JSON.stringify(result));

Running this code will populate the result object with the URL parameters of whatever's on your browser address bar.

If I could improve this in any way, I would have added my favorite RegEx library => [VerbalExpression](https://github.com/VerbalExpressions/JSVerbalExpressions" target="_blank) so I wouldn't have to deal with actual RegExs :)

How do you parse your URL parameters?


  • Share this post on