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.
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: 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: 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! Published on Feb 8, 2018 Tags: Javascript
| JavaScript
| regexp
| urlsearchparams
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
The non-URLSearchParams approach for retrieving query string variables
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, " "));
}
Using URLSearchParams for retrieving query string variables
function getQueryStringParameter(param) {
var params = new URLSearchParams(new URL(location));
return params.get(param);
}
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.