DEV Community

Urban Mixo
Urban Mixo

Posted on

The Illusion of String.length: How to safely count Unicode, Emojis, and Words in JS

If you are building a text input that restricts users to a specific character limit (like a tweet, an SMS gateway, or an SEO meta tag), your first instinct is probably to use String.prototype.length.

If you are doing this in production today, your character counts are fundamentally broken.

Take a look at this standard JavaScript behavior:


javascript
const family = "๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ";
console.log(family.length); // Output: 11

const word = "cafรฉ"; // Formatted with a combining acute accent
console.log(word.length); // Output: 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)