How to know how many words a paragraph contains using Jquery or Javascript? What function?
How to know how many words a paragraph contains using Jquery or Javascript? Wh开发者_Python百科at 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?
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
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.
Using jQuery:
$('p').text().split(' ').length
精彩评论