Follow @endyourif rss Facebook LinkedIn

Retrieving query string variables with JavaScript Retrieving query string variables with JavaScript

Published on Feb 8, 2018

This is not something I use everyday. Seems more like a once a year thing. Last time I needed to extract query string variables, I used the old school approach with a regular expression. Now that I need to do this again, I can use the new school approach: URLSearchParams.

The URLSearchParams (at the time of writing) is not yet standardized in the W3C; however, most modern browsers recognize it.

The non-URLSearchParams approach

Let's start by looking at the old school way using regular expression to compare how much easier it is when browsers begin working together to support ease-of-use:

function getQueryStringParameter(param) {

var url = window.location.href;


param = param.replace(/[\[\]]/g, "\\$&");


var regex = new RegExp("[?&]" + param + "(=([^&#]*)|&|#|$)"),

results = regex.exec(url);


if (!results) return null;

if (!results[2]) return '';


return decodeURIComponent(results[2].replace(/\+/g, " "));


The above code accepts a parameter name and uses a regular expression to find the parameter in the query string. It works in both scenarios where it is the first parameter, e.g. starting with a ?, or when it starts with an &.

Using URLSearchParams

Now the new school way:

function getQueryStringParameter(param) {

var params = new URLSearchParams(new URL(location));


return params.get(param);


If you have used the old school method in the past, I've re-used the existing function and replaced the inside with the new school way. This will help avoid have to find and replace every instance the old regular expression way was used.

In the updated code, a new instance of URLSearchParams is created that accepts a URL object that has been instantiated with the current location. Then using the new params variable, the get function is called with the requested parameter name.


Tags: Javascript | JavaScript | regexp | urlsearchparams

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP