Concatenate Strings with a Separator using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

banner

Photo by Tamara Bellis

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 provide 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee