Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Using jQuery:

$('p').text().split(' ').length
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top