Multiple ways to get query parameters in javascript
- Admin
- Dec 31, 2023
- Javascript
In this tutorial, learn different ways to read query parameters in javascript.
- URLSearchParams
- using Plain javascript code
query parameters are key and value pairs added to url to pass the simple parameters
For example, if url is cloudhadoop.com/about?name=johh&dept=sales.
query parameters are name=johh&dept=sales
In javascript, these are retrieved using
window.location.Search; //name=johh&dept=sales
location.Search; // name=johh&dept=sales
window and location are global javascript objects and window.location and location returns cloudhadoop.com/about
How to get query parameters for the current URL
In the latest browsers, we have URLSearchParams🔗 object used to get query parameters of a given URL.
you can check browser support here🔗
let queryParams = new URLSearchParams(window.location.search);
let name = params.get("name"); // return john
let dept = params.get("dept"); // return sales
The same can also be rewritten using the URL
object with the searchParams
method which returns URLSearchParams
let queryParams = new URL(location.search).searchParams;
let name = params.get("name"); // return john
let dept = params.get("dept"); // return sales
URLSearchParams support: All latest browsers
Plain Javascript code to get query parameters
Here is a utility function which is custom code that returns query key and value pairs in a javascript object.
- Retrieved url query params string using window.location.search
- Split string using = separator
- Iterate each property and separate key and value
function getQuerystring() {
let output={}
if(window.location.search){
var queryParams = window.location.search.substring(1);
var listQueries = queryParams.split("&");
for(var query in listQueries) {
if (listQueries.hasOwnProperty(query)) {
var queryPair = listQueries[query].split('=');
output[queryPair[0]] = decodeURIComponent(queryPair[1] || "");
}
}
}
return output;