smus Posted October 14, 2018 Share Posted October 14, 2018 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). Link to comment Share on other sites More sharing options...
dsonesuk Posted October 14, 2018 Share Posted October 14, 2018 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. Link to comment Share on other sites More sharing options...
smus Posted October 14, 2018 Author Share Posted October 14, 2018 Already solved by changing innerHTML with innerText. Simple and easy Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now