Open In App

Node.js URLsearchParams API

Node.js is an open-source project widely used for the development of dynamic web applications. The URLSearchParams API in Node.js allows read and write operations on the URL query.

The URLSearchParams class is a global object and used with one of the four following constructors.



Constructors:

  1. new URLSearchParams(): No argument constructor instantiates a new empty URLSearchParams object.
  2. new URLSearchParams(string): Accepts a string as an argument to instantiate a new URLSearchParams object.




    var params = new URLSearchParams('user=abc&q=xyz');
    console.log(params.get('user'));
    console.log(params.get('q'));
    
    

    Output:



    abc
    xyz
  3. new URLSearchParams(obj): Accepts an object with a collection of key-value pairs to instantiate a new URLSearchParams object. The key-value pair of obj are always coerced to strings. Duplicate keys are not allowed.




    const params = new URLSearchParams({
      user: 'ana',
      course: ['math', 'chem', 'phys']
    });
    console.log(params.toString());
    
    

    Output:

    user=ana&course=math%2Cchem%2Cphys
  4. new URLSearchParams(iterable): Accepts an iterable object having a collection of key-value pairs to instantiate a new URLSearchParams object. Iterable can be any iterable object. Since URLSearchParams is iterable, an iterable object can be another URLSearchParams, where the constructor will create a clone of the provided URLSearchParams. Duplicate keys are allowed.




    // Using a Map object as it is iterable
    const map = new Map();
    map.set('West Bengal', 'Kolkata');
    map.set('Karnataka', 'Bengaluru');
    params = new URLSearchParams(map);
    console.log(params.toString());
    
    

    Output:

    West+Bengal=Kolkata&Karnataka=Bengaluru

Accessing the URL query:

Manipulating the URL query:

Iterating the URL query:


Article Tags :