How to Generate URL Query Strings in JavaScript

Published Apr 9, 2021

Writing out the URL query string can become cumbersome at times. It gets long and tedious to maintain and fix.

const URI = "";

What if there was a way to generate these query strings from a dictionary mapping of these keys and values?

We can define a generic function to make this translation from map to query string.

const generateQueryString = (params) => {
  return Object.keys(params)
    .map((v, i) => (i !== 0 ? "&" : "?") + `${v}=${o[v]}`)

And then use it like so.

const queryString = generateQueryString({
  key1: "val1",
  key2: "val2",
  key3: "val3"
const URI = "" + queryString;

We can also use the URLSearchParams API to perform the same thing. Fortunately, it’s available on all modern browsers.

const queryString = new URLSearchParams({
  key1: "val1",
  key2: "val2",
  key3: "val3"
// Don't forget the ?
const URI = "" + "?" + queryString;

We can also append to this queryString if needed using append().

queryString.append("key4", "val4");

More JS Articles