property URL.searchParams
The searchParams
property of the URL interface provides a direct interface to
query parameters through a URLSearchParams
object.
This property offers a convenient way to:
- Parse URL query parameters
- Manipulate query strings
- Add, modify, or delete URL parameters
- Work with form data in a URL-encoded format
- Handle query string encoding/decoding automatically
Examples #
#
// Parse and access query parameters from a URL
const myURL = new URL('https://example.org/search?term=deno&page=2&sort=desc');
const params = myURL.searchParams;
console.log(params.get('term')); // Logs "deno"
console.log(params.get('page')); // Logs "2"
// Check if a parameter exists
console.log(params.has('sort')); // Logs true
// Add or modify parameters (automatically updates the URL)
params.append('filter', 'recent');
params.set('page', '3');
console.log(myURL.href); // URL is updated with new parameters
// Remove a parameter
params.delete('sort');
// Iterate over all parameters
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}