How to create and decode a query string in JavaScript

Last updated: October 13, 2022.

To create new query strings in JavaScript without an external library, you can utilize the native URLSearchParams() object constructor.

We also cover how you can extract data from a query string using this constructor.

Table of contents

What is a query string?

A query string is a way of passing data to an API endpoint or another page as part of the URL. The data must be in string format.

Data in a query string is stored in key-value format. Each key-value entry is known as a parameter in a URL.

Below is a valid query string, containing two parameters:

key1=value1&key2=value2

In a URL, a query string is placed after a question mark following the main URL path. For example:

https://example.com/page.html?key1=value1&key2=value2

The parameters are received by the main URL path. The data contained in the paramters can be extracted from there.

Creating a query string

JavaScript provides an in-built object constructor for working with query strings: URLSearchParams().

If your data is in JavaScript object format, your work is made easy. All you have to do is pass in the object to the constructor. Then, on the result, call toString() to extract a query string:

const query = new URLSearchParams({
  name: "Mr Tiddles", 
  type: "Cat",
  human: false,
});

const queryString = query.toString(); // Get output as string

console.log(queryString);
// name=Mr+Tiddles&type=Cat&human=false

For data in another format, you can still use the URLSearchParams() constructor by using the append() method, passing in a key and value.

For example, you can create a loop that appends a value in each iteration:

const query = new URLSearchParams();
const keywords = ["Tutorial", "Simple", "JavaScript"];
for (let i=0; i<keywords.length; i++) {
    query.append('param'+i, keywords[i]);
}
const queryString = query.toString();
console.log(queryString);
// param0=Tutorial&param1=Simple&param2=JavaScript

Adding query string to a URL

Once you have the result, you only need to append it to the end of a URL main path followed by a question mark.

const query = new URLSearchParams();

query.append('param1', 'bacon');
query.append('param2', 'eggs');
query.append('param3', 'cheese');

const queryString = query.toString();

const url = 'https://example.com/page?' + queryString;

window.location.href = url;

The main path will be accessed with the data available as URL parameters.

Extracting data from a query string (URL parameters)

To extract the data from a query string, first pass the URL into the URL() object constructor, accessing on it the searchParams property. This returns the parameters of the URL (query string) only.

To convert the query string to a JavaScript object, you first pass it in to a new instance of URLSearchParams(). Then, on the result, you can call the entries() method to get the data as an array-like object. Array.from() can convert this to an actual array:

const url = window.location.href; // Gets current URL

const searchParams = new URL(url).searchParams; 
// Extracts parameters from URL

const urlSearchParams = new URLSearchParams(searchParams);

const res = Array.from(urlSearchParams.entries());
// Using entries() returns array-like object, Array.from() converts to actual array

console.log(res);
// Example output:
// [
//     [ "name", "Mr Tiddles" ],
//     [ "type", "Cat" ],
//     [ "human", "false" ]
// ]

To convert an array of arrays to a JavaScript object in key-value format, the very useful Object.fromEntries() method is available:

const res = [
    [ "name", "Mr Tiddles" ],
    [ "type", "Cat" ],
    [ "human", "false" ]
];

console.log(Object.fromEntries(res));
// Example output:
// {
//     "name": "Mr Tiddles",
//     "type": "Cat",
//     "human": "false"
// }

Getting individual parameter values

If you are only interest in the values of certain parameters, you can get these by calling the get() method on a URLSearchParams() object that has had some contents passed into it:

const url = window.location.href;

const searchParams = new URL(url).searchParams; 
const urlSearchParams = new URLSearchParams(searchParams);

urlSearchParams.get('param1'); // Returns value of param1

Summary

A query string is an efficient way to send simple string data to another URL location as part of a URL itself.

The URLSearchParams() object constructor can be used to construct and deconstruct query strings. In the latter case, URL().searchParams can be used to get a query string attached to an existing URL.

The beauty of this solution is that the data is contained in the URL itself. If used to pass data from one page to another, it therefore doesn't assume any capability of a user's browser beyond running JavaScript.

But if you need data to persist beyond the next page (e.g. for the entire session or every time the user visit your site), you should consider storing data in a user's browser using the localStorage API.