JavaScript: how to create a query string with URLSearchParams

JavaScript: how to create a query string with URLSearchParams

In this article we will see how to create a query string with the JavaScript URLSearchParams object.

In this article we will see how to create a query string with the JavaScript URLSearchParams object.

We need to create an instance of the object and using its method append() specifying the key and the value.


'use strict';

const params = new URLSearchParams();

params.append('foo', '1');
params.append('bar', 'test');

So to get the query string we call the toString() method.


const queryString = params.toString();

console.log(queryString); // 'foo=1&bar=test