[Home] > Snippets  > Languages  > JavaScript  > Strings  >  Count the number of words in a string

Count the number of words in a string

JavaScript

const countWords = (str) => str.trim().split(/\s+/).length

TypeScript

const countWords = (str: string): number => str.trim().split(/\s+/).length

Examples

countWords('Hello World') // 2
countWords('Hello World') // 2
countWords(' Hello World ') // 2