Word count is wrong when adding new line in contenteditable
contenteditable, counter, html, javascript, jquery
Solution
You can use this:
$("#post_content").children().each(function(index, el){buffer += $(el).text()+"\n"})
This way you iterate by all elements inside your `div` and get only the text, put a "\n" between them.
Problem
I count the words in a `contenteditable`. I split it using spaces. The problem comes when you enter a new line. It doesn’t count the word you’re currently writing on the new line until you add a space. On top of that, in the following example if you split the example text into two lines, it will “eat up” one word when you do that: http://jsfiddle.net/MrbUK/ I’m guessing this issue exists because between HTML elements there are no spaces: `<div>some things</div><div>are cool</div>` its string would be “some thingsare cool”. Here’s the code that I have: ``` function wordCount() { var content_text = $('#post_content').text(), char_count = content_text.length, word_count = 0; // if no characters, words = 0 if (char_count != 0) word_count = content_text.replace(/[^\w ]/g, "").split(/\s+/).length; $('.word_count').html(word_count + " words • " + char_count + " characters"); } ``` I tried replacing some HTML tags: ``` word_count = content_text.replace(/ /g, " ").replace(/<div>/g, "<p>").replace(/<\/div>/g, "</p>").replace(/<\/p><p>/g, " ").split(/\s+/).length; ``` without any luck. I need to discard whether it’s a `<p>` or `<div>` and some browsers add ` ` when merging lines together. Any ideas? Thanks! EDIT: Thanks to Jefferson below for his clever method, I managed to solve this. For some reason I have to do -1 on the `word_count` to display the correct number of words: ``` function wordCount() { var content_div = $('#post_content'), content_text, char_count = content_div.text().length, word_count = 0; // if no characters, words = 0 if (char_count != 0) content_div.children().each(function(index, el) { content_text += $(el).text()+"\n"; }); // if there is content, splits the text at spaces (else displays 0 words) if (typeof content_text !== "undefined") word_count = content_text.split(/\s+/).length - 1; $('.word_count').html(word_count + " words • " + char_count + " characters"); } ```