QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Count Words in a String

Counts the number of words in a string.

  • string
  • manipulation
  • word count
  • count

Install

npx shadcn@latest add https://quicksnip.dev/r/count-words-in-a-string.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

function countWords(str) {
  return str.trim().split(/\s+/).length;
}

Usage

countWords('Hello world! This is a test.'); // Returns: 6