Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 1 min read

Why a Twitter/X character counter can't just use JavaScript .length

When you're writing for X, one character is not always one counted unit. JavaScript strings use UTF-16; visual glyphs can span several code points; and X's public weighted-character rules treat many CJK characters and em

When you're writing for X, one character is not always one counted unit. JavaScript strings use UTF-16; visual glyphs can span several code points; and X's public weighted-character rules treat many CJK characters and emoji differently from Latin text.

Three examples make the difference clear:

"Hello world" is 11 weighted characters.
"δΈ­ζ–‡" has 2 visible glyphs but a weighted length of 4.
"https://example.com" typically has a fixed recognized URL weight of 23, not its literal text length.
Using str.length on the whole message misses all of this. Twitter's open-source twitter-text parser is a better reference for standard posts:

js import twitterText from 'twitter-text'; console.log(twitterText.parseTweet('δΈ­ζ–‡ https://example.com').weightedLength);

It is still a reference parser, not a live validation of every current X account or premium long-post feature. I built a small browser-only counter to compare visible length, URL count, emoji count and X's weighted length, with a plain post preview. Try it if you need to check a draft: https://postchars.com/twitter-character-counter/?utm_source=devto&utm_medium=article&utm_campaign=x_counter

Full background and examples: https://postchars.com/guides/twitter-urls-emoji-counting/

What edge cases have you seen with emoji sequences or internationalized URLs?

Editorial notes: Explain the concept first, link once or twice only. Do not pretend to be an official X source. Review DEV policy; optionally set canonical_url to the on-site guide when content is substantially duplicated.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.