Join non-Empty Strings with a Separator in JavaScript

avatar

Borislav Hadzhiev

Mon Nov 29 20212 min read

Join non-Empty Strings with a Separator #

To join non-empty strings with a separator, add the strings to an array and call the filter() method on the array to filter only for truthy values, e.g. [str1, str2].filter(Boolean).join(','). The filter method will return an array that contains no empty strings.

index.js
const str1 = ''; const str2 = 'apple'; let str3; const str4 = 'banana'; const joined = [str1, str2, str3, str4].filter(Boolean).join(','); console.log(joined); // ๐Ÿ‘‰๏ธ "apple,banana"

The first step is to add the strings to an array, so we can call the Array.filter method on it.

The filter method takes a function and calls it for every element in the array.

We passed the Boolean object as the function to the filter method, which is identical to doing the following:

index.js
const str1 = ''; const str2 = 'apple'; let str3; const str4 = 'banana'; const joined = [str1, str2, str3, str4] .filter(element => Boolean(element)) .join(','); console.log(joined); // ๐Ÿ‘‰๏ธ "apple,banana"
Either way, if the conversion of the string to boolean returns true, it gets added to the array the filter method returns.

The Boolean object converts all falsy values to false and all truthy values to true.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

All other values get converted to true, meaning if the string contains at least 1 character, the Boolean object will convert it to true and it will be added to the array that the filter method returns.

The last step is to join the array elements into a string using the Array.join method.

The join method takes a separator as a parameter and joins the array elements into a string based on the provided separator.

Here are some examples.

index.js
console.log(['a', 'b', 'c'].join('_')); // ๐Ÿ‘‰๏ธ "a_b_c" console.log(['a', 'b', 'c'].join(',')); // ๐Ÿ‘‰๏ธ "a,b,c" console.log(['a', 'b', 'c'].join(' ')); // ๐Ÿ‘‰๏ธ "a b c" console.log(['a', 'b', 'c'].join('')); // ๐Ÿ‘‰๏ธ "abc"

Because the array is already filtered and contains no empty strings, undefined or null values, the final string won't have two separators next to one another.

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