Convert array to string with brackets and quotes in JavaScript

featured Image

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:

Compare Elements Of Two Arrays In JavaScript

Javascript – Convert array to String (with and without commas)

5 ways to convert string to number in JavaScript

Replace all occurrences of a string in JavaScript

Create multiline string in JavaScript | Split string to Multilines

How to create Multiline string in JavaScript?

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more