Use-Cases of this Tutorial
- Know how to convert an array to a string by joining its elements.
- Know about Array.join() method.
A Javascript array can be converted to a string by using the join() method to join elements of the array separated by a given character or string.
Converting an array to a string is very commonly required in Javascript programming. To handle this we have the join() method.
The join() method concatenates all elements of the calling array with a given separator string between each pair of elements. The combined string is returned.
Example - Array to string by joining elements with a space :
var arr = [ "As", "the", "cheerless", "towns", "pass", "my", "window" ];
var combined = arr.join(" ");
console.log(combined);
// "As the cheerless towns pass my window"
Example - Array to string by joining elements with a comma and space :
var arr = [ "John", "David", "Jack", "Veronica", "Raj" ];
var combined = arr.join(", ");
console.log(combined);
// "John, David, Jack, Veronica, Raj"
Example - Array to string by joining elements with newline and line break :
var arr = [ "John", "David", "Jack", "Veronica", "Raj" ];
var combined = arr.join("\n\r");
console.log(combined);
/*
"John
David
Jack,
Veronica
Raj"
*/