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. I’ve also got a version of this for how-to Access query string parameters with Express and Node.js.
The non-URLSearchParams approach for retrieving query string variables
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 by using the Javascript string replace() method:
[code]
function getQueryStringParameter(param) {
var url = window.location.href;
param = param.replace(/[\[\]]/g, “<a href=”file://$&”>\\$&</a>”);
var regex = new RegExp(“[?&]” + param + “(=([^&#]*)|&|#|$)”),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return ”;
return decodeURIComponent(results[2].replace(/\+/g, ” “));
}
[/code]
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 for retrieving query string variables
Now the new school way:
[code]
function getQueryStringParameter(param) {
var params = new URLSearchParams(new URL(location));
return params.get(param);
}
[/code]
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!