URLSearchParams JavaScript Method

URLSearchParams is a built-in JavaScript class that provides a convenient way to manipulate and extract query parameters from a URL string. It allows you to parse, modify, and construct query strings easily. This class simplifies tasks such as retrieving and updating query parameters in a URL.

Here’s a detailed explanation of URLSearchParams with examples:

  1. Parsing Query Parameters: URLSearchParams can parse query parameters from a URL string. Let’s consider the following URL:
const url = new URL('https://example.com/search?query=JavaScript&page=1');
const params = new URLSearchParams(url.search);

In this example, we create a new URL object using the URL string. Then, we extract the query parameters by passing url.search to the URLSearchParams constructor. The resulting params object represents the query parameters.

  1. Getting Query Parameters: URLSearchParams provides various methods to retrieve query parameters. Here are a few examples:
  • get(name): Retrieves the value of the specified parameter.
const query = params.get('query'); // 'JavaScript'
const page = params.get('page');   // '1'
  • getAll(name): Retrieves an array of all values for the specified parameter.
const colors = new URLSearchParams('color=red&color=blue&color=green');
const colorValues = colors.getAll('color'); // ['red', 'blue', 'green']
  • has(name): Checks if a parameter with the given name exists.
const hasQuery = params.has('query'); // true
const hasSort = params.has('sort');   // false
  • keys(): Returns an iterator over the parameter names.
for (const key of params.keys()) {
  console.log(key);
}
  1. Modifying Query Parameters: URLSearchParams allows you to modify query parameters easily. Here are a few examples:
  • set(name, value): Sets the value of the specified parameter.
params.set('query', 'TypeScript');
  • append(name, value): Appends a new value to the specified parameter.
params.append('tag', 'javascript');
  • delete(name): Removes the specified parameter.
params.delete('page');
  • toString(): Returns the query parameters as a string.
const newQueryString = params.toString();
  1. Creating a New Query String: You can create a new query string using URLSearchParams by adding parameters and then calling toString(). Here’s an example:
const newParams = new URLSearchParams();
newParams.append('name', 'John');
newParams.append('age', '25');
const newQueryString = newParams.toString(); // 'name=John&age=25'

URLSearchParams provides a powerful and intuitive interface for working with query parameters in JavaScript. It simplifies tasks related to parsing, retrieving, modifying, and constructing URL query strings.