Jump to content
smus

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×