JavaScript: Convert Array to a String
How do you convert an array to a string in JavaScript?
The standard way is to use the built-in toString() method.
You can also take advantage of JavaScript’s type coercion: the +
operator can either add two numbers or concatenate two strings. But what happens when you try to join an object (an array []
is also an object) with something else? JavaScript is forgiving so it won’t crash our program, instead it does know how to concatenate strings, so it will convert everything into a string.
A slightly less common approach is to use the join() method. By default it adds a comma to resulting values, though you can also specify that it add nothing or some other separator value.
What if you have a nested array? That is, an array with an array inside it? Here you need to use JSON.stringify()
.
Finally, if you can’t use a built-in method for some reason, you can loop through the array and convert it to a string manually.
// 1. Use .toString()
['a', 'b', 'c'].toString(); // 'a,b,c'
// 2. Coerce to string
['a', 'b', 'c'] + []; // 'a,b,c'
['a', 'b', 'c'] + ''; // 'a,b,c'
// 3. Use .join()
['a', 'b', 'c'].join(); // 'a,b,c' (defaults to ',' separator)
['a', 'b', 'c'].join(''); // 'abc'
['a', 'b', 'c'].join('-'); // 'a-b-c'
// 4. Use JSON.stringify()
JSON.stringify(['a', [1], 'b', 'c']); // '['a', [1], 'b','c']'
// 5. Manually, if can't use built-in method...
function arrayToString(arr) {
let str = '';
arr.forEach(function(i, index) {
str += i;
if (index != (arr.length - 1)) {
str += ',';
};
});
return str;
}
Want to improve your JavaScript? I have a list of recommended JavaScript books.