Jump to content

Counting the words in a text

Recommended Posts

What if I should count all the words in a text, that is not in a single tag. For example, there are a few <p> tags:

<p>first paragraph</p><p>second paragraph</p><p>third paragraph</p>

function countwords(){
		var p = document.getElementsByTagName("p"), n = document.getElementById("n"), a=[],text = "", count = 0;
		for(var x=0;x<p.length;x++){
		  text = p[x].innerHTML;
		  text = text.trim();
		  a = text.split(" ");
		  al = a.length;
		  count = count + al;	
		n.innerHTML = count;

It works fine if I put a relatively small text. When I put there a pretty long text (around 300 words), the result is not correct.

Does it count double or triple spaces between the words? But MS Word gives even higher result (374 instead of around 360 words).

Share this post

Link to post
Share on other sites

A better idea would be to strip all tags and assign that! to a variable, trim, then count what's left.

As for MS word count,  It would be hard for it i imagine to distinguish from tags such as span, div, or class, id  attributes and values, from actual words, so it will include those as well.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...