How to Convert an Object to and from a URL Query String in JavaScript
When working with web requests, you frequently need to handle URL query strings (the part of a URL after the ?, like page=2&limit=10). This involves two main operations: converting a JavaScript object into a query string to build a URL, and parsing a query string from a URL back into an object.
This guide will teach you the modern and standard methods for both of these tasks using the powerful, built-in URLSearchParams API.
Object to Query String: How to Build a Query String
The URLSearchParams constructor provides the simplest and most robust way to convert an object into a URL-encoded query string.
For example, we have a JavaScript object of parameters and need to convert it into a valid query string to append to a URL.
// Problem: How to convert this object to "?page=2&limit=10&filter=js"?
const params = {
page: 2,
limit: 10,
filter: 'js',
};
The recommended solution uses new URLSearchParams(): simply pass your object to the URLSearchParams constructor and call the .toString() method on the result.
const params = {
page: 2,
limit: 10,
filter: 'js & css', // Note the special characters
};
const queryString = new URLSearchParams(params).toString();
console.log(queryString); // Output: "page=2&limit=10&filter=js+%26+css"
Important: The .toString() method returns the query string without the leading question mark (?). You typically prepend it yourself when building the final URL.
const finalUrl = `https://example.com/api/items?${queryString}`;
console.log(finalUrl);
// Output: "https://example.com/api/items?page=2&limit=10&filter=js+%26+css"
This method automatically handles URL-encoding special characters (like & becoming %26), making it safe and reliable.
Query String to Object: How to Parse a Query String
The URLSearchParams constructor is also used for the inverse operation: parsing a query string into a useful object.
For example, we have a query string from a URL (e.g., from window.location.search) and need to extract the values of its parameters.
// Problem: How to get the values of 'page' and 'filter' from this string?
const queryString = '?page=3&filter=js';
The recommended solution uses new URLSearchParams(): pass the query string (including the ?) to the constructor. This creates a URLSearchParams object with helpful methods for accessing the data.
const queryString = '?page=3&filter=js&tags=a&tags=b';
const searchParams = new URLSearchParams(queryString);
// --- Get a specific parameter ---
console.log(searchParams.get('page')); // Output: "3"
// --- Check if a parameter exists ---
console.log(searchParams.has('filter')); // Output: true
console.log(searchParams.has('sort')); // Output: false
// --- Get all values for a parameter that appears multiple times ---
console.log(searchParams.getAll('tags')); // Output: ['a', 'b']
This object is the standard way to work with query parameters. However, if you need a plain JavaScript object, you can use Object.fromEntries().
const queryString = '?page=3&filter=js';
const searchParams = new URLSearchParams(queryString);
const plainObject = Object.fromEntries(searchParams);
console.log(plainObject); // Output: { page: '3', filter: 'js' }
Working with the URLSearchParams Object
The URLSearchParams object is iterable and provides several useful methods for manipulation:
const searchParams = new URLSearchParams('?page=1');
// --- Add or update a parameter ---
searchParams.set('page', '2');
searchParams.append('limit', '10'); // Use append to add a key that may already exist
// --- Delete a parameter ---
searchParams.delete('limit');
// --- Iterate over the parameters ---
for (const [key, value] of searchParams) {
console.log(`${key}: ${value}`);
}
// Output: page: 2
// --- Get the final string ---
console.log(searchParams.toString());
// Output: page=2
Conclusion
The URLSearchParams API is the definitive, modern tool for handling URL query strings in JavaScript.
- To create a query string from an object, use
new URLSearchParams(obj).toString(). - To parse a query string, pass it to the
new URLSearchParams(queryString)constructor and use methods like.get()and.has()to access the data. - To get a plain object from a query string, use
Object.fromEntries(new URLSearchParams(queryString)).
By using this built-in API, you can ensure your query strings are correctly formatted, encoded, and parsed according to web standards.