Concatenate Strings with a Separator using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Concatenate Strings with a Separator #

To concatenate strings with a separator, add the strings to an array and call the join() method on the array, passing it the separator as a parameter. The join method returns a string, where all array elements are joined using the provided separator.

index.js
const str1 = 'one'; const str2 = 'two'; const str3 = 'three'; const commaSeparated = [str1, str2, str3].join(','); console.log(commaSeparated); // 👉️ "one,two,three" const hyphenSeparated = [str1, str2, str3].join('-'); console.log(hyphenSeparated); // 👉️ "one-two-three"
You can specify any string as the separator, e.g. an underscore, a word, a space, etc.

We used the Array.join method to concatenate multiple strings with a separator.

The only parameter the join() method takes is the separator that is added between the array elements when converting them to a string.

If you omit the separator parameter, the array elements are converted into a comma-separated string.
index.js
const str1 = 'one'; const str2 = 'two'; const str3 = 'three'; const withoutSeparator = [str1, str2, str3].join(); console.log(withoutSeparator); // 👉️ "one,two,three"
Even if that's what you need, it's a best practice to be explicit and pass the comma to the join() method, as not all developers are aware of the default behavior.

If the join method is called on an empty array, an empty string is returned.

index.js
console.log([].join(',')); // 👉️ ""

Note that any undefined, null, or empty array [] values get converted to an empty string.

index.js
// 👉️ "one,two," console.log(['one', 'two', undefined].join(','));
If you see a trailing separator in the result, chances are your array contains an undefined, null or [] value.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.