Borislav Hadzhiev
Sun Nov 14 2021·2 min read
Photo by Lisha Riabinina
To count the unique characters in a string, convert the string to a Set
to
remove all the duplicate characters and access the size
property on the Set
,
e.g. new Set(str).size
. The size
property will return the number of unique
characters in the string.
const str = 'hello world'; // ✅ Unique Char Count const uniqueCount = new Set(str).size; console.log(uniqueCount); // 8 // ✅ Get Unique Chars const uniqueStr = [...new Set(str)].join(''); console.log(uniqueStr); // 👉️ helo wrd // ✅ Remove Spaces from unique Chars const withoutSpaces = uniqueStr.replaceAll(' ', ''); console.log(withoutSpaces); // 👉️ helowrd
We used the
Set()
constructor to convert the string to a Set
object.
The Set()
constructor takes an iterable, such as a string, array, etc, and
converts it to a Set
.
const str = 'hello world'; // 👇️ {'h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'} console.log(new Set(str));
Set objects only store unique values, so any of the duplicate characters are automatically excluded.
To get the unique character count, we access the
size
property on the Set
object.
The second example shows how to get the unique characters in the string:
Set
Set
to an arrayIf you want to remove the spaces from the string, you can use the replaceAll()
method to replace any spaces with an empty string.
// 👇️ 'abc' console.log('a b c'.replaceAll(' ', ''));
The two parameters we passed to the replaceAll
method are:
The method returns a new string where all occurrences of the substring are replaced by the provided replacement.
If you don't want to count spaces as unique characters, you can access the
length
property on the replaced version of the string.
const str = 'hello world'; const count = [ ...new Set(str) ].join('').replaceAll(' ', '').length; console.log(count); // 👉️ 7
This gets us the count of unique characters, excluding all spaces.