Borislav Hadzhiev
Last updated: Jul 23, 2022
Check out my new book
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.
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"
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.
separator
parameter, the array elements are converted into a comma-separated string.const str1 = 'one'; const str2 = 'two'; const str3 = 'three'; const withoutSeparator = [str1, str2, str3].join(); console.log(withoutSeparator); // 👉️ "one,two,three"
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.
console.log([].join(',')); // 👉️ ""
Note that any undefined
, null
, or empty array []
values get converted to
an empty string.
// 👉️ "one,two," console.log(['one', 'two', undefined].join(','));
undefined
, null
or []
value.