W3docs

How to Encode JavaScript Object to Query-String

Read this JavaScript tutorial and learn useful information about the two widely used methods that are used for encoding objects to query strings easily.

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 <kbd class="highlighted">encodeURIComponent()</kbd> 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:

Javascript encodes a Uniform Resource Identifier (URI) component

javascript— editable

URLSearchParams()

The URLSearchParams interface specifies utility methods to work with the query string of a URL:

Javascript URLSearchParams interface

javascript— editable

Or by passing the search object into the constructor like this:

Javascript URLSearchParams interface

javascript— editable

The <kbd class="highlighted">toString()</kbd> method of the URLSearchParams interface returns a query string suitable for use in a URL. And the <kbd class="highlighted">append()</kbd> method of the interface appends a specified key or value pair as a new search parameter.