When you are building a web application, you often need to get the values of query string parameters from a URL. In this blog post, we’ll learn how to retrieve these values using JavaScript.
Understanding Query Strings
A query string is a part of the URL that contains data in the form of key-value pairs. It starts with a question mark ?
followed by the key-value pairs separated by ampersands &
. The key and value in each pair are separated by an equals sign =
.
For example, consider the following URL:
https://example.com/search?q=javascript&sort=popularity&page=2
The query string in this URL is ?q=javascript&sort=popularity&page=2
, and it has the following key-value pairs:
q=javascript
sort=popularity
page=2
Querying String Parameters in JavaScript
In modern browsers, the URLSearchParams
object makes it easy to work with query strings. Here’s a function that uses URLSearchParams
to retrieve the value of a specific query string parameter:
function getQueryStringParam(param) {
const queryParams = new URLSearchParams(window.location.search);
return queryParams.get(param);
}
Using this function, you can get the value of any query string parameter by providing its key as an argument. For example, to get the value of the q
parameter in the example URL, you would use:
const searchQuery = getQueryStringParam("q");
console.log(searchQuery); // Output: "javascript"
If the specified parameter is not present in the query string, the function will return null
.
Handling Older Browsers
If you need to support older browsers that don’t have URLSearchParams
, you can use the following function:
function getQueryStringParam(param) {
const query = window.location.search.substring(1);
const params = query.split("&");
for (let i = 0; i < params.length; i++) {
const keyValue = params[i].split("=");
if (keyValue[0] === param) {
return decodeURIComponent(keyValue[1]);
}
}
return null;
}
This function works by first getting the query string without the leading question mark, then splitting it into an array of key-value pairs. It then loops through the array and splits each pair into a key and value. If the key matches the desired parameter, it returns the value after decoding it with decodeURIComponent
to handle special characters.
Conclusion
In this blog post, we’ve learned how to retrieve query string parameters from a URL using JavaScript. By utilizing the built-in URLSearchParams
object or a custom function for older browsers, you can easily access the values of query string parameters in your web applications.