How to Convert a Set to a String in JavaScript

Last updated on June 02, 2022
How to Convert a Set to a String in JavaScript

To convert a set to a string in JavaScript, call the Array.from() method with the Set as an argument, then call the join() method on the resulting array. For example:

const set = new Set(['x', 'y', 'z']);

const str1 = Array.from(set).join(' ');
console.log(str1); // x y z

const str2 = Array.from(set).join(',');
console.log(str2); // x,y,z

The Array.from() method converts an array-like object like a Set into an array:

const set = new Set(['x', 'y', 'z']);

console.log(Array.from(set)); // [ 'x', 'y', 'z' ]

After the conversion, we can call the join() method on the array. join() returns a string containing the elements of an array concatenated with the specified separator:

console.log(['x', 'y', 'z'].join('-')); // x-y-z

console.log(['x', 'y', 'z'].join('/')); // x/y/z

Note: We can also use the spread syntax (...) to convert a Set to an array:

const set = new Set(['x', 'y', 'z']);

const str1 = [...set].join(' ');
console.log(str1); // x y z

const str2 = [...set].join(',');
console.log(str2); // x,y,z

The spread syntax unpacks the values of the Set into a new array that we call join() on to get the string.

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

See also