Table of Contents
You can convert a JavaScript array to a string using the built-in toString
method.
When you use this method, it will return a string of your array's elements separated by commas.
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5];
const numbersString = numbers.toString();
console.log(numbersString);
// "1,2,3,4,5"
If you want to convert an array of objects to a string of their values, you can first convert the object to JSON, then log it to the console.
JAVASCRIPTconst obj = [
{
name: "New York",
country: "USA"
},
{
name: "Paris",
country: "France"
},
{
name: "London",
country: "UK"
}
];
const objString = JSON.stringify(obj);
console.log(objString);
// [{"name":"New York","country":"USA"},{"name":"Paris","country":"France"},{"name":"London","country":"UK"}]
Array to String without Commas
When you want to convert an array to a string without commas, you can use the join
method. This method is called on an array and joins each element together with a specified separator.
JAVASCRIPTconst numbers = [1, 2, 3, 4, 5];
numbers.join(); // "1,2,3,4,5"
numbers.join("-"); // "1-2-3-4-5"
numbers.join(" "); // "1 2 3 4 5"
Now you know how to convert a JavaScript array to a string, with or without commas!
Leave us a message!
×
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor