In a URL, the query string refers to the portion of the URL that follows the question mark ”?” symbol. It is used to pass data or parameters to a web server or web application. The query string consists of one or more key-value pairs separated by ampersands ”&“.
const url = new URL("https://example.com/search?q=apple&category=fruits&page=1");
console.log(url.search);
//=> '?q=apple&category=fruits&page=1'
The query string provides a way to include additional information in a URL, such as search terms, filters, sorting options, pagination details, or any other data that needs to be passed between web pages or applications.
The URLSearchParams API is a native JavaScript API available in modern browsers. It provides methods to parse, modify, and format query strings. You can use it to extract and manipulate individual parameters, add or remove parameters, and stringify JavaScript objects into query strings.
The URL interface has a property called searchParams, which returns a URLSearchParams object that can be used to access, modify, and iterate over the query parameters in the same order as they appear in the URL.
// Create a URL object from a string
const url = new URL('https://example.com?foo=1&bar=2');
// Get a URLSearchParams object from the URL object
const params = url.searchParams;
// Use the URLSearchParams methods to access and modify the query parameters
console.log(params.get('foo')); // '1'
params.set('foo', '3');
console.log(params.toString()); // 'foo=3&bar=2'
The URLSearchParams interface also has a constructor that can take a string, an object, or another URLSearchParams object as an argument.
// Create a URLSearchParams object from a query string
const params = new URLSearchParams('?foo=bar&baz=qux');
// Get the value of a parameter
console.log(params.get('foo')); // 'bar'
// Set the value of a parameter
params.set('foo', 'new');
// Delete a parameter
params.delete('baz');
// Iterate over the parameters
for (const [key, value] of params) {
console.log(key, value);
}
// Stringify the parameters
console.log(params.toString()); // 'foo=new'
URLSearchParams is a native web API that is widely supported by modern browsers and has a simple and consistent interface. However, it also has some limitations:
new URLSearchParams({foo: {bar: 'baz'}})
will produce foo=[object Object]
instead of foo[bar]=baz
.?
off of a string, if present.encodeURIComponent()
.=
, and a parameter that doesn’t have a =
altogether.If you need more features or flexibility, you might want to use an open source library that can handle more complex scenarios and edge cases. For example, some popular libraries for working with query strings are:
import qs from 'qs';
var parsed = qs.parse('a=b&c=d&e[f]=g');
console.log(parsed);
//=> {a: 'b', c: 'd', e: {f: 'g'}}
var stringified = qs.stringify({a: 'b', c: 'd', e: {f: 'g'}});
console.log(stringified);
//=> 'a=b&c=d&e[f]=g'
import queryString from 'query-string';
const parsed = queryString.parse('?foo=bar&baz=qux');
console.log(parsed);
//=> {foo: 'bar', baz: 'qux'}
const stringified = queryString.stringify({foo: 'bar', baz: 'qux'});
console.log(stringified);
//=> 'foo=bar&baz=qux'
import urlcat from 'urlcat';
// Build a URL with path parameters
const url = urlcat('https://api.example.com', '/users/:id/posts', { id: 42 });
console.log(url);
//=> 'https://api.example.com/users/42/posts'
// Build a URL with query parameters
const url2 = urlcat('https://api.example.com', '/users', { limit: 10, offset: 20 });
console.log(url2);
//=> 'https://api.example.com/users?limit=10&offset=20'