Convert array to string with brackets and quotes in JavaScript
Short article on how to convert an array to a string while preserving brackets and quotes.
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:
Related Posts
Capitalize First Letter of a String - JavaScript
This article is about how to capitalize the first letter of a string using JavaScript.
Check if String starts with a space in JavaScript
Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.
JavaScript - Detect if a string contains any space
FInd out how to detect if a string contains any white space using regex test() method and string indexOf() method in Javascript.
Split a String into chunks of N character into an array in JavaScript
Find out how to split String into Substrings by length of N characters in JavaScript using split(), match() and substr() methods.
