How to Concatenate Strings in an Array using JavaScript
Jun 11, 2021
JavaScript's join()
method is handy for turning elements in an array into a string.
JavaScript arrays can contain values of different types.
If you only want to concatenate strings, you can filter out non-string values using filter()
and typeof
as shown below.
let array = ['The', 97, 'Dream', 'Team'];
let jumble = array.join();
jumble; // 'The 97 Dream Team'
let text = array.filter(v => typeof v === 'string').join();
text; // The Dream Team
Separators
You can specify what character to use to concatenate the elements in the array.
Simply pass the string you want to use.
If you do not provide the character, it will default to using a ,
:
let array = ['user', 'desktop', 'learning', 'tutorials'];
let concatenate = array.join('/');
concatenate; // user/desktop/learning/tutorials
array.join(); // user,desktop,learning,tutorials
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard