Guides

How to count words in a string in JavaScript — and why split(" ") lies

Illustration: a row of wooden word tiles with a few empty space tiles slipped in between

You're building a form — "Tell us about yourself, up to 300 words" — and ask an AI to add a counter. It writes one line:

const words = text.split(" ").length

Looks reasonable. You open the form — the field is empty, and the counter says 1 word. You type "Hello — world" — it says 3. Add two spaces in a row — the word count goes up, even though you didn't write anything.

Let's build a counter that doesn't lie. Four steps, with a ready function at the end.

Step 1. Understand why split(" ") is wrong

split(" ") cuts a string at every single space. Exactly one. And it faithfully returns whatever ended up between them — even nothing.

  • Empty string: "".split(" ") gives [""]. An array with one empty item — length 1.
  • Two spaces in a row: there's an empty piece between them, and it counts too.
  • A line break isn't a space. "end\nstart" becomes one word.
  • A dash sits alone between spaces, so "—" counts as a word.

On real text: for a line like " Someone wrote «hello» — and 3.5 million people replied!" with a line break and a couple more words, the naive way counted 13 words. There were really 10.

Step 2. Drop the emptiness: trim and any whitespace

The first improvement is to cut not at one space, but at any run of whitespace. And to trim whitespace at the edges.

function countWords(text) {
  const trimmed = text.trim()
  if (trimmed === "") return 0
  return trimmed.split(/\s+/).length
}

What's going on here:

  1. trim() removes spaces and line breaks at the start and end.
  2. The empty string is handled separately — otherwise we'd get 1 again.
  3. /\s+/ means "one or more spaces, tabs or line breaks in a row". Two spaces are now one cut.

Much better already. But dashes and lone quotes still count as words.

Step 3. Count words, not gaps

Flip the approach. Instead of "cut at spaces", say: "find all the words". A word is letters and digits in a row. A hyphen, apostrophe, dot or comma inside counts too, so "well-known", "it’s" and "3.5" don't fall apart.

const WORD = /[\p{L}\p{N}]+(?:[-’'.,][\p{L}\p{N}]+)*/gu

function countWords(text) {
  return (text.match(WORD) || []).length
}

Let's break the regex down:

  1. \p{L} — any letter of any alphabet: Latin, Cyrillic, Greek.
  2. \p{N} — any digit.
  3. (?:[-’'.,]...)* — a word may continue through a hyphen, apostrophe, dot or comma if letters follow.
  4. The u flag turns on Unicode; without it \p{...} doesn't work. The g flag means find all matches, not just the first.

|| [] is there because match returns null, not an empty array, when nothing matches.

The same text now gives 10 words. The dash is skipped, "well-known" is one word, "3.5" is one number. Exactly how a person would count.

Step 4. Add languages without spaces

Some languages don't separate words with spaces at all: Japanese, Chinese, Thai. For "こんにちは世界" ("hello, world") the regex finds one long "word".

The browser's built-in Intl.Segmenter helps here. It knows language dictionaries and cuts text at real word boundaries:

const segmenter = new Intl.Segmenter("ja", { granularity: "word" })
const parts = [...segmenter.segment("こんにちは世界")]
parts.filter(p => p.isWordLike).length // 2

isWordLike filters out spaces and punctuation. It works in all modern browsers and in Node.

Why not use it everywhere? It splits "well-known" and "e-mail" into two words. For English and Russian the step 3 result is more familiar. So we build a hybrid: if the text has Chinese characters, Japanese kana or Thai — Segmenter, otherwise — the regex.

const WORD = /[\p{L}\p{N}]+(?:[-’'.,][\p{L}\p{N}]+)*/gu
const NO_SPACES = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}]/u

function countWords(text) {
  if (NO_SPACES.test(text)) {
    const seg = new Intl.Segmenter(undefined, { granularity: "word" })
    return [...seg.segment(text)].filter(p => p.isWordLike).length
  }
  return (text.match(WORD) || []).length
}

What you get

Hook the function up to the field — and the counter behaves like a proper editor:

textarea.addEventListener("input", () => {
  const n = countWords(textarea.value)
  counter.textContent = `${n} / 300`
})
  • Empty field — 0, not 1.
  • Extra spaces and line breaks add nothing.
  • "Well-known", "it’s" and "3.5" — one word each, a dash — zero.
  • Japanese text is counted by words, not as one chunk.

As a bonus you can show reading time: divide the word count by 200 and round up — that's a rough adult reading speed, in minutes.

How do I count characters correctly?

text.length counts encoding pieces, not characters. The emoji "👋🏽" gives 4. For an honest character limit use Intl.Segmenter with granularity: "grapheme" — it counts what the eye sees.

Can I count AI tokens this way?

No. Models count tokens, not words, and there are usually more tokens than words — especially in languages other than English. For model limits you need that model's tokenizer.

Why do I get a different number than Word?

Editors settle edge cases differently: numbers, website addresses, words joined by a slash. A difference of a couple of words is normal. What matters is that your counter is consistent and doesn't count emptiness.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →