Convert a Set to a String in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

banner

Photo by Matthew Henry

Convert a Set to a String in JavaScript #

To convert a Set to a string, pass the Set to the Array.from() method to convert it to an array and call the join() method on the result, e.g. const str = Array.from(set).join(' '). The join method returns a string where the array elements are joined by the provided separator.

index.js
const set1 = new Set(['a', 'b', 'c']); // โœ… Using Array.from // ๐Ÿ‘‡๏ธ "a b c" const str1 = Array.from(set1).join(' '); console.log(str1); // ๐Ÿ‘‡๏ธ "a,b,c" const str2 = Array.from(set1).join(','); console.log(str2);

We used the Array.from method to convert a Set to an array.

index.js
const set1 = new Set(['a', 'b', 'c']); // ๐Ÿ‘‡๏ธ ['a', 'b', 'c'] console.log(Array.from(set1));

We did the conversion, so we can call the join() method on the array.

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

index.js
// ๐Ÿ‘‡๏ธ "a_b_c" console.log(['a', 'b', 'c'].join('_')) // ๐Ÿ‘‡๏ธ "a b c" console.log(['a', 'b', 'c'].join(' '))
We used an underscore and a space in the examples, however you can provide whatever separator suits your use case, e.g. an empty string for no separator at all.
index.js
// ๐Ÿ‘‡๏ธ "abc" console.log(['a', 'b', 'c'].join(''))

A very common alternative to using the Array.from method is to use the spread syntax (...) to convert a Set to an array.

index.js
const set1 = new Set(['a', 'b', 'c']); // ๐Ÿ‘‡๏ธ "a b c" const str1 = [...set1].join(' '); console.log(str1); // ๐Ÿ‘‡๏ธ "a,b,c" const str2 = [...set1].join(','); console.log(str2);

These examples achieve the same result as the first two, however this time we used the spread syntax (...) to unpack the Set values into an array, on which we can call the join() method.

The spread syntax can be used with iterables such as a Set, string, another array, etc.

The spread syntax (...) is more commonly used, however it doesn't play well with TypeScript in some scenarios, and the Array.from method does.

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