How to Get Query String Parameters in JavaScript
📌 Introduction
A query string is the part of a URL that comes after the ? symbol. It contains key-value pairs separated by & and is commonly used to pass data between pages. 🌐
>>"Query strings are the bridge for passing small pieces of data through the URL."
🔑 Example of a Query String
Sample URL
https://example.com/page?user=Sathish&age=25&city=ChennaiIn this URL:
- user=Sathish
- age=25
- city=Chennai
⚙️ Getting Query Strings with window.location
Raw Query String
console.log(window.location.search);
// Output: "?user=Sathish&age=25&city=Chennai"The location.search property gives you the entire query string, including the ?. But usually, you’ll want to parse it. 🔎
🧩 Modern Way: URLSearchParams
Using URLSearchParams
let params = new URLSearchParams(window.location.search);
console.log(params.get("user")); // "Sathish"
console.log(params.get("age")); // "25"
console.log(params.get("city")); // "Chennai"URLSearchParams makes it easy to work with query strings:
- params.get("key") → Gets the value of a parameter.
- params.has("key") → Checks if a parameter exists.
- params.keys() → Returns all parameter names.
- params.entries() → Loops through all key-value pairs.
💡 Example: Looping Through All Parameters
Iterating Params
let params = new URLSearchParams(window.location.search);
for (let [key, value] of params.entries()) {
console.log(key, "=", value);
}
// Output:
// user = Sathish
// age = 25
// city = Chennai📜 Legacy Way: Custom Function
Manual Parsing
function getQueryParam(name) {
let url = window.location.search;
let params = new URLSearchParams(url);
return params.get(name);
}
console.log(getQueryParam("user")); // "Sathish"🧠 Practical Use Cases
- Passing user data between pages (e.g., ?user=123).
- Filtering and sorting products in an e-commerce site. 🛒
- Tracking campaigns with UTM parameters (?utm_source=google).
- Deep linking to specific page states.
⚠️ Things to Remember
Note
- Query strings are visible in the URL → don’t store sensitive data. 🔐
- Values are always returned as string → convert if needed.
- Encoding/decoding may be needed for spaces and special characters.
🌟 Conclusion
JavaScript makes it easy to read query strings using location.searchand the URLSearchParams API. Whether for filtering, tracking, or navigation, query strings are a simple yet powerful way to pass data between pages. 🚀
Learn more on MDN