JavaScript : String.length is not the count of characters

31 Aug 2022

In JavaScript, String.length does not represent the count of characters. Rather they represent the count of codepoints. Since the normal characters can be represented using single codepoints, in most cases we get String.length is the same as the count of characters.

But as we start using unicode characters, which uses more than one codepoint to represent a single character, we start getting wrong character counts.

For Eg. "💊".length will provide the length as 2.

unicode length

So, How do we find the correct character length when unicode characters are involved?

Using spread operator

The easiest way to find the character length is to convert the string into an array using the spread operator and then find the length of the array

[...`💊💊💊💊`].length  // 4

using spread operator

Hope that helped.
Thank You.

If you find my work helpful, You can buy me a coffee.