Convert a Set to a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Convert a Set to a String in JavaScript #

To convert a Set to a string:

  1. Pass the Set to the Array.from() method to convert it t an array.
  2. Call the join() method on the array.
  3. The join method will join the array elements into a string based on 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 to join the array elements without a separator.
index.js
// 👇️ "abc" console.log(['a', 'b', 'c'].join(''))

Alternatively, you can use the spread operator (...) instead of Array.from().

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);

This time we used the spread syntax (...) to unpack the Set values into an array before calling the join() method.

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

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.