Sling Academy
Home/JavaScript/How to Pass a JavaScript Array within a Query String

How to Pass a JavaScript Array within a Query String

Last updated: March 22, 2023

A query string is part of a URL (Uniform Resource Locator) that contains data or parameters to be passed to a web application. The query string starts with a question mark (?) and is followed by key-value pairs separated by an ampersand (&).

This concise, example-based article will walk you through a couple of different approaches to passing a JavaScript array within a query string.

Using the JSON.stringify() method

We can use the JSON.stringify() method to convert the array into a string and pass it as a parameter in the query string. On the receiving end, we can parse the JSON string back into an array using the JSON.parse() method.

Example:

// an array of ids
const ids = [1, 2, 3, 4, 5];

//converting array to a string and passing it as a parameter in the query string
const queryString = '?ids=' +  encodeURIComponent(JSON.stringify(ids));

const myUrl = 'https://www.example.com/products' + queryString;
console.log(myUrl)

Output:

https://www.example.com/products?ids=%5B1%2C2%2C3%2C4%2C5%5D

The encodeURIComponent() function allows you to encode special characters in your query string that would otherwise change the meaning of your query string. Characters like +, /, and & are special.

You can extract and get back the array of ids like so:

// create a URL object from the string
const url = new URL(myUrl);

// get the query string
const receivedQueryString = url.searchParams.get('ids');

// convert the query string to an array
const receivedIds = JSON.parse(receivedQueryString);
console.log(receivedIds);

Using the join() method

Caution: Don’t use this technique if your array contains special characters like commas or semicolons because it will not work as expected.

An alternative approach is to use the join() method to convert the array into a string with a separator and pass it as a parameter in the query string. On the receiving end, we can split the string back into an array using the split() method.

Example:

//creating an array of strings
const fruits = ['apple', 'banana', 'mango', 'orange'];

//converting array to a string and passing it as a parameter in the query string
const queryString = '?fruits=' + fruits.join(',');

const url = 'https://www.slingacademy.com/fruits' + queryString;
console.log(url)

Output:

https://www.slingacademy.com/fruits?fruits=apple,banana,mango,orange

If you want your URL to look cooler and more professional, just call the encodeURIComponent() function:

//creating an array of strings
const fruits = ['apple', 'banana', 'mango', 'orange'];

//converting array to a string and passing it as a parameter in the query string
let queryString = '?fruits=' + fruits.join(',');

// call the encodeURIComponent() function
queryString = encodeURIComponent(queryString);

const url = 'https://www.slingacademy.com/fruits' + queryString;
console.log(url)

And the result will become this:

https://www.slingacademy.com/fruits%3Ffruits%3Dapple%2Cbanana%2Cmango%2Corange

On the receiving end (a backend API, for example), you can get back the array like so:

const urlObject = new URL(url);
const fruitsArray = urlObject.searchParams.get('fruits').split(',');
console.log(fruitsArray)

That’s it. Happy coding & have a nice day!

Next Article: JavaScript: 3 Ways to Find the Product of a Numeric Array

Previous Article: JavaScript: 3 Ways to Create Multidimensional Arrays

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration