views:

403

answers:

4

How to know how many words a paragraph contains using Jquery or Javascript? What function?

For example, the sentence

How to know how many words a paragraph contains using Jquery or Javascript?

contains 13 words. How to count using Jquery or javascript?

+6  A: 

If you take the word separator to be whitespace:

function wordCount(str) {
  return str.split(/\s+/).length
}

wordCount("How to know how many words \
           a paragraph contains using Jquery \
           or Javascript?"); // 13
Crescent Fresh
+3  A: 

You can get the textContent (or innerText for IE) of the p element, and count the words, assuming that a word is a group of characters separated by a space.

You could do something like this:

function wordNumber (element) {
  var text = element.innerText || element.textContent;
  return text.split(' ').length;
}

alert(wordNumber(document.getElementById('paragraphId')));

Try the above snippet here.

CMS
This fails on text with newlines/tabs/multiple-spaces/etc in it, inside `<pre>` elements or any element with css `white-space:pre;` set.
Crescent Fresh
I know, I should use `/\s+/` to split...
CMS
+1  A: 

using jQ:

$('p').text().split(' ').length

prodigitalson
A: 

no of count down word using in java script

kalidhasan