Count the Unique Characters in a String in JavaScript

avatar

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.

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee