How to Get URL Parameters with JavaScript

URL parameters (also called query strings) are a crucial part of web development, allowing you to pass data between pages or from client to server. Whether you’re building a search feature, handling form submissions, or tracking user preferences, knowing how to extract and use these parameters is essential.
In this article, I’ll show you the most effective ways to get URL parameters using JavaScript, from modern approaches to legacy solutions.
Key Takeaways
URLSearchParams
is the modern, recommended way to handle URL parameters- Use
urlParams.get('param')
to retrieve a single parameter value - Use
urlParams.has('param')
to check if a parameter exists - For older browsers, implement a custom parsing function
- Always decode parameter values to handle special characters
- Be aware of security implications when using URL parameters
Understanding URL Parameters
URL parameters appear after the question mark (?
) in a URL and are formatted as key-value pairs:
https://example.com/page?name=john&id=123
In this example, there are two parameters: name
with a value of john
and id
with a value of 123
.
The Modern Approach: URLSearchParams
The simplest and most reliable way to handle URL parameters in modern browsers is using the URLSearchParams
interface.
Basic Usage
// Assuming URL: https://example.com/page?product=shirt&color=blue&size=m
// Get the query string
const queryString = window.location.search;
// Parse the query string
const urlParams = new URLSearchParams(queryString);
// Get a specific parameter value
const product = urlParams.get('product'); // "shirt"
const color = urlParams.get('color'); // "blue"
Checking If a Parameter Exists
// Check if a parameter exists
if (urlParams.has('product')) {
// Parameter exists
console.log('Product parameter exists');
}
Handling Multiple Values
If a parameter appears multiple times in the URL, you can retrieve all values:
// URL: https://example.com/page?tag=javascript&tag=frontend
// Get all values for a parameter
const tags = urlParams.getAll('tag'); // ["javascript", "frontend"]
Iterating Over Parameters
URLSearchParams
provides iterator methods to work with all parameters:
// Iterate over all parameter keys
for (const key of urlParams.keys()) {
console.log(key);
}
// Iterate over all parameter values
for (const value of urlParams.values()) {
console.log(value);
}
// Iterate over all parameter entries (key-value pairs)
for (const [key, value] of urlParams.entries()) {
console.log(`${key}: ${value}`);
}
Legacy Approach: Custom Function
For older browsers that don’t support URLSearchParams
, you can create a custom function:
function getUrlParam(param) {
const queryString = window.location.search.substring(1);
const urlParams = queryString.split('&');
for (let i = 0; i < urlParams.length; i++) {
const paramPair = urlParams[i].split('=');
if (paramPair[0] === param) {
return decodeURIComponent(paramPair[1] || "");
}
}
return null;
}
// Usage
const productValue = getUrlParam('product');
Handling Common Edge Cases
Encoded Characters
URL parameters often contain encoded characters. For example, spaces are encoded as %20
:
// URL: https://example.com/search?query=web%20development
const query = urlParams.get('query');
console.log(query); // "web development" (automatically decoded)
When using a custom function, make sure to use decodeURIComponent()
to handle these encoded characters correctly.
Missing Parameters
Always check if a parameter exists before using it:
const size = urlParams.has('size') ? urlParams.get('size') : 'default';
Empty Parameters
Parameters can exist without values:
// URL: https://example.com/page?newsletter=&theme=dark
const newsletter = urlParams.get('newsletter'); // "" (empty string)
const hasNewsletter = urlParams.has('newsletter'); // true
Complete Example: Getting All URL Parameters
Here’s a comprehensive function to get all URL parameters as an object:
function getAllUrlParams() {
const params = {};
const queryString = window.location.search.substring(1);
if (queryString) {
const pairs = queryString.split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=');
// If the parameter has no value, set it to true
if (typeof value === 'undefined') {
params[key] = true;
} else {
// If we already have this parameter, convert to array
if (params[key]) {
if (!Array.isArray(params[key])) {
params[key] = [params[key]];
}
params[key].push(decodeURIComponent(value));
} else {
params[key] = decodeURIComponent(value);
}
}
}
}
return params;
}
Browser Compatibility
URLSearchParams
is supported in all modern browsers, including:
- Chrome 49+
- Firefox 44+
- Safari 10.1+
- Edge 17+
For older browsers like Internet Explorer, you’ll need to use a polyfill or the custom function approach.
Performance Considerations
For most applications, the performance difference between methods is negligible. However:
URLSearchParams
is optimized and maintained by browser vendors- Custom functions can be tailored to your specific needs
- If you’re only getting a single parameter, a simple regex might be faster
Security Notes
Remember that URL parameters are visible in the browser’s address bar and are not secure for sensitive information. Always validate and sanitize parameter values before using them in your application.
Conclusion
The URLSearchParams
interface provides a clean, standardized way to work with URL parameters in JavaScript. For most modern web applications, it’s the recommended approach. For legacy browser support, a custom function can provide the same functionality with a bit more code.
By understanding how to effectively extract and use URL parameters, you can build more dynamic and interactive web applications.
FAQs
Yes, you can use URLSearchParams to modify parameters and then update the URL with history.pushState() or history.replaceState().
Most SPA frameworks (React, Vue, Angular) have built-in routing systems that handle URL parameters. Check your framework's documentation for details.
Parameter names are case-sensitive according to the URL specification, so 'name' and 'Name' are different parameters.
You can use the same parameter name multiple times (e.g. ?color=red&color=blue) or use bracket notation (e.g. ?colors[]=red&colors[]=blue).
There's no official limit, but browsers and servers typically have practical limits around 2,000-8,000 characters for the entire URL.