Array to string in JavaScript
Converting an array into a string in JavaScript. Three cases:
- A separator is indicated
- No separator
- Converting an array into a word
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.
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>
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
- Array.prototype.join(): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
- 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
- Adding a class to all sibling elements of a specific type in JavaScript
- Detecting a newly generated element and adding a class to it in JavaScript
- Detect if a class has been added (JavaScript)
- Getting the last class name in classList collection
- Removing the last character from a string in Javascript