Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript [Solved] Is There A Jquery API to count words? Reply To: Is There A Jquery API to count words?

#153700
__
Participant

You don’t need jQuery for this. It would be way overkill.

// get the text you want to count
var txt = "The quick brown fox jumped over the lazy dog";

// a regex that matches individual words
var word = /\b\w+\b/g;

// this is a counter, 0 words to start
c = 0;

// loop: increment counter as long as you keep finding words
while( r = word.exec( txt ) ){ c += 1; }

// see how many words you found
alert( c );

pen

@jamy just saw your response – problem is, what happens when you have multiple spaces between words?