Count the number of words in a string
Count runs of non-whitespace characters.
function countWords(text) { return (text.match(/\S+/g) || []).length; }
Input & expected output
Input
"Small code, working integrations."Expected output
4The edge case
Input
" "Expected output
0Know the limits
- The original split on whitespace and returned 1 for a blank string; this version returns 0.
- Punctuation attached to a word is part of it.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Count the number of words in a string from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Counts non-whitespace runs; the original returned 1 for a blank string. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/count-the-number-of-words-in-a-string.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Capitalize a string — Uppercase the first Unicode code point and preserve the remaining text.
- Reverse a string — Reverse Unicode code points without splitting surrogate pairs.
- Check a palindrome — Compare a string with its code-point reversal.