- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Introduction to URLSearchParams API in Node.js
Node is an open source project that is used to create dynamic web applications. The URLSearchParams API is an interface. It defines different utility that is required to work with the query string of the URL.
In this article, we will discuss the four different constructors of URLSearchParams that can be used as per the requirement.
new URLSearchParams()
This is a no argument constructor and therefore only used to initialize a new Empty URLSearchParams() object.
Syntax
var params = new URLSearchParams();
new URLSearchParams(string)
This constructor can accept a string as an input parameter along with instantiating a new URLSearchParams object.
Syntax
const params = new URLSearchParams('firstName=pqr & lastName=xyz'); console.log(params.get('firstName')); console.log(params.get('lastName'));
Output
pqr xyz
new URLSearchParams(object)
This contructor accepts an object as an input parameter with a collection of key-value pairs to initialize a new URL. The key-value pair are always converted to string type. Duplicate keys are not allowed.
Syntax
const params = new URLSearchParams({ user: 'John', subjects: ['Physics', 'Chemistry', 'Maths'] }); console.log(params.toString());
Output
user=John&subjects=Physics%2CChemistry%2CMaths
new URLSearchParams(iterable)
This contructor accepts an iterable object that contains a collection of key-value pairs to initialize a new URLSearchParams object. Since URLSearchParams is itself an iterable an object, therefore we can have another iterable URLSearchParams inside new URLSearchParams(). Duplicate keys are allowed inside this.
Syntax
const map = new Map(); map.set('Taj Mahal', 'Agra'); map.set('Qutub Minar', 'Delhi'); map.set('Gateway of India', 'Mumbai'); params = new URLSearchParams(map); console.log(params.toString());
Output
Taj+Mahal=Agra&Qutub+Minar=Delhi&Gateway+of+India=Mumbai