📜  Node.js URLsearchParams API(1)

📅  最后修改于: 2023-12-03 14:44:40.723000             🧑  作者: Mango

Node.js URLSearchParams API

The URLSearchParams API is a part of the Node.js url module, which provides methods for working with URL query strings. With this API, you can easily create, manipulate, and parse URL search parameters.

Creating a URLSearchParams Object

To create a URLSearchParams object, you can pass a query string as the first parameter to the constructor. For example:

const { URLSearchParams } = require('url');

const params = new URLSearchParams('key1=value1&key2=value2');

This will create a new URLSearchParams object with the key1=value1 and key2=value2 parameters.

Adding and Removing Parameters

You can add and remove parameters using the set, append, and delete methods:

const { URLSearchParams } = require('url');

const params = new URLSearchParams('key1=value1');

params.set('key2', 'value2');
params.append('key3', 'value3');
params.delete('key1');
Retrieving Parameters

You can retrieve a parameter value using the get method:

const { URLSearchParams } = require('url');

const params = new URLSearchParams('key1=value1&key2=value2');

const value1 = params.get('key1');

You can also get all parameter values for a key using the getAll method:

const { URLSearchParams } = require('url');

const params = new URLSearchParams('key1=value1&key2=value2&key1=value3');

const values = params.getAll('key1');
Stringifying Parameters

To convert a URLSearchParams object back to a string, you can use the toString method:

const { URLSearchParams } = require('url');

const params = new URLSearchParams('key1=value1&key2=value2');

const queryString = params.toString();
Conclusion

Overall, the URLSearchParams API provides an easy and versatile way to work with URL query strings in Node.js. With its many methods for adding, removing, and retrieving parameters, you can easily manipulate query strings to meet your needs.