문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top