Reading Query String Variables in JavaScript

This short snippet will show you how to read Query String variables using JavaScript.


Published on:September 22, 2014
HEADS UP! This article is valid (the code works as advertised), but may or may not represent represent best practices. It has not been reviewed.

Every so often we come across one of those 'gotchas' when working with JavaScript. One such 'gotcha' is reading query string variables from the URL. Oddly enough JavaScript has no built in way to do this. Luckily it's easy enough for us to implement our own such function:


 function queryString(item){
    let value = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)","i"));
    return decodeURIComponent(value ? value[1] : value);
  }

To use this function, simply do:


queryString("variableName")

This will return the contents of the query string variable variableName or null if it doesn't exist. That's all there is to it! Thanks for reading!