To retrieve query string values in JavaScript, you can parse the URL parameters using vanilla JavaScript or modern APIs like URLSearchParams
. Below is a detailed guide with multiple examples and edge-case handling.
1. What is a Query String?
A query string is part of a URL that contains data in the format:
?key1=value1&key2=value2&key3=value3
- It starts with
?
and uses&
to separate key-value pairs. - Example:
https://example.com?name=John&age=30
.
2. Access the Query String
Use window.location.search
to get the query string from the current URL:
const queryString = window.location.search; // Returns "?name=John&age=30"
3. Parsing Methods
Method 1: Using URLSearchParams
(Modern Approach)
The URLSearchParams
API provides built-in methods to work with query strings.
Example 1: Basic Usage
const urlParams = new URLSearchParams(window.location.search);
// Get a specific parameter
const name = urlParams.get('name'); // "John"
const age = urlParams.get('age'); // "30"
// Check if a parameter exists
if (urlParams.has('name')) {
console.log('Name exists');
}
// Get all parameters as an object
const params = Object.fromEntries(urlParams.entries());
console.log(params); // { name: "John", age: "30" }
Example 2: Handling Multiple Values
If a parameter appears multiple times (e.g., ?hobbies=reading&hobbies=gaming
):
const hobbies = urlParams.getAll('hobbies'); // ["reading", "gaming"]
Example 3: Iterate Over All Parameters
urlParams.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
Limitations of URLSearchParams
:
- Does not automatically handle nested objects/arrays.
- Returns values as strings (e.g.,
"30"
instead of30
).
Method 2: Manual Parsing (Traditional Approach)
Use this method if you need more control or support for older browsers.
Example 1: Basic Parsing Function
function getQueryParams() {
const params = {};
const queryString = window.location.search.substring(1);
const pairs = queryString.split('&');
for (const pair of pairs) {
if (!pair) continue; // Skip empty pairs
const [key, value] = pair.split('=', 2); // Split on the first "="
const decodedKey = decodeURIComponent(key.replace(/\+/g, ' '));
const decodedValue = decodeURIComponent((value || '').replace(/\+/g, ' '));
// Handle multiple values (e.g., ?color=red&color=blue → ["red", "blue"])
if (params.hasOwnProperty(decodedKey)) {
params[decodedKey] = [].concat(params[decodedKey], decodedValue);
} else {
params[decodedKey] = decodedValue;
}
}
return params;
}
// Usage:
const queryParams = getQueryParams();
console.log(queryParams.name); // "John"
Example 2: Edge Cases
- Empty Value:
?key=
→{ key: "" }
- No Value:
?key
→{ key: "" }
- Encoded Characters:
?name=John%20Doe
→{ name: "John Doe" }
- Special Characters:
?query=a%26b%3Dc
→{ query: "a&b=c" }
4. Handling Data Types
Convert query string values to specific types (e.g., numbers, booleans, arrays).
Example 1: Numbers
const age = parseInt(queryParams.age); // "30" → 30
Example 2: Booleans
const isActive = queryParams.active === 'true'; // "true" → true
Example 3: Arrays
// For ?hobbies=reading,gaming (comma-separated)
const hobbies = queryParams.hobbies.split(',');
5. Advanced Use Cases
Case 1: Nested Objects
For a query string like ?user[name]=John&user[age]=30
:
const params = getQueryParams();
const user = {
name: params['user[name]'],
age: params['user[age]']
};
Case 2: Dynamic Parameter Creation
Build a query string from an object:
const params = { name: "John", age: 30 };
const queryString = new URLSearchParams(params).toString(); // "name=John&age=30"
6. Browser Compatibility
URLSearchParams
: Supported in all modern browsers (Chrome 49+, Firefox 29+, Edge 17+).- Manual Parsing: Works in all browsers, including IE.
7. Best Practices
- Always Decode Values: Use
decodeURIComponent
to handle spaces (+
or%20
) and special characters. - Validate Input: Check if a parameter exists before using it.
- Type Conversion: Convert strings to numbers/booleans where necessary.
- Use
URLSearchParams
: Prefer it for simplicity unless you need legacy support.
Summary
- For modern browsers, use
URLSearchParams
. - For legacy support or complex cases, use a manual parsing function.
- Always handle edge cases like missing values, duplicates, and encoding.
Try the live demo to experiment with query string parsing!