New urlsearchparams javascript

URLSearchParams is a JavaScript API that allows you to work with the query string of a URL. It was introduced in ECMAScript 2015 (ES6) and is supported in modern browsers.

Here are some key features and methods of URLSearchParams:

Creating a URLSearchParams object

You can create a URLSearchParams object from a URL string using the URLSearchParams() constructor:

const url = new URLSearchParams('key=value&foo=bar');

Alternatively, you can create an empty URLSearchParams object and add parameters to it using the set() method:

const url = new URLSearchParams();
url.set('key', 'value');
url.set('foo', 'bar');

Getting and setting parameters

You can get a parameter value using the get() method:

const value = url.get('key'); // returns "value"

You can set a parameter value using the set() method:

url.set('key', 'new value');

You can also use the delete() method to remove a parameter:

url.delete('foo');

Iterating over parameters

You can iterate over the parameters using the forEach() method:

url.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});

Other methods

Example usage

Here's an example of using URLSearchParams to work with a URL query string:

const url = new URL('https://example.com/path?key=value&foo=bar');
const params = new URLSearchParams(url.search);

console.log(params.get('key')); // outputs "value"
params.set('key', 'new value');
console.log(params.toString()); // outputs "key=new+value&foo=bar"