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:

serialize = function (obj) {
  let str = [];
  for (let p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}
console.log(serialize({
  prop1: "hi there",
  prop2: "100%"
}));
// prop1=hi%20there&prop2=100%25

URLSearchParams()

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

const searchParams = new URLSearchParams();
const search = {
  prop1: "hi there",
  prop2: "100%"
};
Object.keys(search).forEach(key => searchParams.append(key, search[key]));
console.log(searchParams.toString());

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

const obj = {
  prop1: "hi there",
  prop2: "100%"
};
const params = new URLSearchParams(obj).toString();
console.log(params);

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.

Do you find this helpful?

Related articles