Convert array to string with brackets and quotes in JavaScript


This article is about how to convert an array to a string with brackets and quotes.

Let's say you have an array with names of fruits like this.

["Banana", "Orange", "Mango"];

And you want to print it out in the DOM as a string "["Banana", "Orange", "Mango"]" with its bracket and quotes just like an array.

So how do we do it?

Well to convert it into a string while preserving its brackets and quotes we can just use the JSON.stringify() method.

The JSON.stringify() method converts a JavaScript object or value to a JSON (JavaScript Object Notation) string

Example:

const fruits = ["Banana", "Orange", "Mango"];
const fruitsStr = JSON.stringify(fruits)

console.log(fruitsStr)

Output:

'["Banana","Orange","Mango"]'

If you want to check if it's a string or not, you can use the typeof keyword like this

console.log(typeof fruitsStr) //string

Related Topics:

Append Item To Array In JavaScript

JavaScript : 5 Ways To Empty An Array

Compare Elements Of Two Arrays In JavaScript

How To Convert An Array To String In Javascript


💾 Recommended Articles