Count the Unique Characters in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 14, 2021

banner

Photo from Unsplash

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.

index.js
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.

index.js
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.

index.js
// 👇️ '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.

index.js
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.

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.