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
.
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
Hope that helped.
Thank You.