Count Characters in Text — With and Without Spaces
Count characters in any text with options to include or exclude spaces. Understand the difference between characters, code points, and grapheme clusters for accurate character counting.
Detailed Explanation
Character Counting: More Than Meets the Eye
Character counting appears trivial — just use .length on a string, right? In practice, "character" can mean different things depending on the context, and getting an accurate count requires understanding Unicode.
Basic Character Count
The simplest approach counts all characters including spaces:
const totalChars = text.length;
const charsNoSpaces = text.replace(/\s/g, "").length;
However, JavaScript's .length returns the number of UTF-16 code units, not the number of visible characters. This distinction matters for emoji and certain scripts.
Characters vs. Code Points vs. Grapheme Clusters
Consider the emoji "👨💻" (man technologist). It is:
- 10 UTF-16 code units —
"👨💻".length === 7in JavaScript (the actual value depends on the encoding of ZWJ sequences) - 4 Unicode code points —
[...text].lengthgives code point count - 1 grapheme cluster — what the user perceives as a single character
For user-facing character counts, grapheme clusters are usually the correct unit:
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemeCount = [...segmenter.segment(text)].length;
With vs. Without Spaces
Most character counters offer both modes:
| Mode | Includes | Use Case |
|---|---|---|
| With spaces | All characters | SMS limits, database field lengths |
| Without spaces | Only non-whitespace | Translation pricing, typesetting |
Special Characters
- Newlines (
\n,\r\n) — counted as 1 or 2 characters depending on the platform - Tabs (
\t) — always 1 character regardless of visual width - Zero-width characters —
\u200B(zero-width space),\uFEFF(BOM) are invisible but counted
Practical Limits
Common character limits: Twitter/X posts (280), SMS messages (160 for GSM-7, 70 for Unicode), meta descriptions (155-160), and HTML title tags (50-60). Knowing the exact character count helps stay within these boundaries.
Use Case
Character counting is critical for social media posts (Twitter/X 280-char limit), SMS messages (160-char limit), SEO meta descriptions (155-160 chars), database field validation, and translation services that charge per character. Developers also use it to validate form input lengths.