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

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.