Categories
JavaScript Answers

How to convert array to string while preserving brackets with JavaScript?

Spread the love

Sometimes, we want to convert array to string while preserving brackets with JavaScript.

In this article, we’ll look at how to convert array to string while preserving brackets with JavaScript.

How to convert array to string while preserving brackets with JavaScript?

To convert array to string while preserving brackets with JavaScript, we can use the JSON.stringify method.

For instance, we write:

const a = [
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5],
  [1, 2, 3, 4, 5]
];
const s = JSON.stringify(a);
console.log(s)

We call JSON.stringify with a to convert the array a to a string.

Therefore, s is '[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]'.

Conclusion

To convert array to string while preserving brackets with JavaScript, we can use the JSON.stringify method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *