Retrieving query string variables with JavaScript

Published on Feb 8, 2018 by Jamie Munro

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.

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 &.

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.

Enjoy!

Tags: Javascript | JavaScript | regexp | urlsearchparams

Related Posts

blog comments powered by Disqus