How to Encode JavaScript Object to Query-String
The query-string is the part of a URL where data is transferred to a web application or back-end database. You need query strings because the HTTP protocol is stateless by design. The query string consists of query parameters and sends data to the server. In this tutorial, we suggest fast and simple methods that will help you encode a Javascript Object into a query-string.
encodeURIComponent()
The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component. It replaces each instance of certain characters by one, two, three, or four escape sequences and represents the UTF-8 encoding of the character.
The new ES6 format encodes objects to query string in the following way:
URLSearchParams()
The URLSearchParams interface specifies utility methods to work with the query string of a URL:
Or by passing the search object into the constructor like this:
The toString() method of the URLSearchParams interface returns a query string suitable for use in a URL. And the append() method of the interface appends a specified key or value pair as a new search parameter.