New urlsearchparams
URLSearchParams
is a web API that allows you to work with the query string of a URL. It provides a way to easily manipulate and parse the query string, which is the part of the URL that comes after the ?
character.
Here are some common methods and properties of URLSearchParams
:
Methods:
get(name)
: Returns the value of the query parameter with the given name.set(name, value)
: Sets the value of the query parameter with the given name.append(name, value)
: Appends a new query parameter with the given name and value.delete(name)
: Deletes the query parameter with the given name.has(name)
: Returns a boolean indicating whether the query parameter with the given name exists.keys()
: Returns an iterator over the names of the query parameters.values()
: Returns an iterator over the values of the query parameters.entries()
: Returns an iterator over the key-value pairs of the query parameters.
Properties:
toString()
: Returns the query string as a string.toString()
: Returns the query string as a string.
Here's an example of how you might use URLSearchParams
:
const urlParams = new URLSearchParams('name=John&age=30');
console.log(urlParams.get('name')); // Output: "John"
console.log(urlParams.get('age')); // Output: "30"
urlParams.set('name', 'Jane');
console.log(urlParams.toString()); // Output: "name=Jane&age=30"
urlParams.append('city', 'New York');
console.log(urlParams.toString()); // Output: "name=Jane&age=30&city=New York"
urlParams.delete('age');
console.log(urlParams.toString()); // Output: "name=Jane&city=New York"
URLSearchParams
is supported in modern browsers, including Chrome, Firefox, and Edge. You can also use it in Node.js using the url
module.
Note that URLSearchParams
is not the same as the querystring
module in Node.js, although it serves a similar purpose. URLSearchParams
is a more modern and flexible API that is designed to work with the query string of a URL, whereas querystring
is a module that provides a way to parse and manipulate query strings in a more general sense.