- 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
Query-string encoding of a Javascript Object
The query string is made up of query parameters and used to send data to the server. This part of the URL is optional. It needs to be constructed by the developer. This can be done using a native method called encodeURIComponent.
The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character
Using the new ES6 format, objects can be query string encoded in the following way −
Example
let obj = { name: 'John', age: 25, city: 'Chicago' }; let qs = Object.keys(obj) .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`) .join('&'); console.log(qs);
Output
This will give the output −
name=John&age=25&city=Chicago
Advertisements