Count the Unique Characters in a String in JavaScript


Borislav Hadzhiev

Sun Nov 14 20212 min read

Count the Unique Characters in a String #

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 = [ 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:

  1. Convert the string to a Set
  2. Convert the Set to an array
  3. Join the array of characters back to a string

If 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:

  1. a substring to match in the string
  2. the replacement for each match

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 = [ Set(str) ].join('').replaceAll(' ', '').length; console.log(count); // 👉️ 7

This gets us the count of unique characters, excluding all spaces.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.