KOMPX.COM or COMPMISCELLANEA.COM   

Array to string in JavaScript

Converting an array into a string in JavaScript. Three cases:

  1. A separator is indicated
  2. No separator
  3. Converting an array into a word

1. Array to string with a separator

All elements of an array are concatenated, separated by a dash or minus sign:

HTML code:


<div class="example"></div>

JavaScript code:


<script>
var theArray = ['one','two','three'];
var resultString = theArray.join('-');

// Printing the resulting string
document.querySelector('.example').textContent = resultString;
</script>

Note: if there is just one element in an array, then it is going to be returned without any separators.

2. Array to string with no separator indicated

All elements of an array are concatenated and since there is no separator given, comma is used as the default:

HTML code:


<div class="example2"></div>

JavaScript code:


<script>
var theArray = ['one','two','three'];
var resultString = theArray.join();

// Printing the resulting string
document.querySelector('.example2').textContent = resultString;
</script>

3. Converting an array into a word

All elements of an array are concatenated. The separator is an empty string, so all elements are glued into one single word:

HTML code:


<div class="example3"></div>

JavaScript code:


<script>
var theArray = ['one','two','three'];
var resultString = theArray.join('');

// Printing the resulting string
document.querySelector('.example3').textContent = resultString;
</script>

Links

  1. Array.prototype.join(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
  2. JavaScript Array join(): w3schools.com/jsref/jsref_join.asp
Browser support
Windows
Internet Explorer 4.0+
Edge 12.0+
Firefox 1.0+
Google Chrome
Opera 4.0+
Safari 3.1+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 4.04+
Linux
Firefox 1.0+
Google Chrome / Chromium
Opera 4.0+
SeaMonkey 1.0+
Mozilla 0.6+
Netscape 4.04+
Hv3
iOS
Safari 1.0+
Android
Samsung Internet 1.0+
Chrome 18.0+
Firefox 4.0+
Opera 10.1+
More