Skip to main content

Count Words in String

countWordsโ€‹

Counts the number of words in a string, supporting multiple languages and scripts. This function uses a Unicode-aware regular expression to accurately identify words across different writing systems.

Function Signatureโ€‹

export function countWords(text: string): number

Parametersโ€‹

NameDescription
textThe input string to count words from.

Returnsโ€‹

Returns the number of word-like tokens found in the string.

Exampleโ€‹

countWords('Hello world!'); // 2
countWords('ใ“ใ‚Œใฏใƒ†ใ‚นใƒˆใงใ™'); // 1
countWords('123 apples, 456 oranges'); // 4

Aliasesโ€‹

  • countWordsInString: Alias for countWords
  • wordCount: Alias for countWords

Notesโ€‹

  • This function is Unicode-aware and supports letters with diacritics, punctuation like apostrophes, and hyphenated words.
  • Numbers are counted as words.

Conclusionโ€‹

Use countWords to accurately determine word count in multilingual or mixed-content strings. Ideal for input validation, content analysis, and linguistic metrics.