简体   繁体   中英

Word counter ignoring words after carriage return

I have this:

 var editor = document.getElementById('editor'); var words = document.querySelector('.words'); function wordsCount() { var arr = editor.textContent.trim().replace(/\\s+/g, ' ').split(' '); words.textContent = !arr[0] ? 0 : arr.length; } editor.addEventListener('input', wordsCount); wordsCount(); 
 body { width: max-content; font-family: 'Helvetica'; } section { outline: 2px solid #BFDEFF; } aside { background-color: silver; } 
 <section id="editor" contenteditable="true">Default text</section> <aside class="words"></aside> 

The problem is that the script ignores words after a carriage return. So, if I type,

Example
Example
Example

it only counts one word instead of three. Any help?

There are no line breaks to begin with. Let's see what happens when you enter those three lines:

Example
Example
Example

The editor element's HTML now looks as follows:

<section id="editor" contenteditable="true">Example<div>Example</div><div>Example</div></section>

Instead of line breaks, new lines are wrapped by <div> elements.

Now, accessing editor.textContent returns the concatenation of the textContent property value of all child nodes. Thus, it returns ExampleExampleExample .

To fix your problem, you could replace editor.textContent with editor.innerText or simply use a <textarea> instead.

 const editor = document.getElementById('editor'); const output = document.getElementById('counter'); editor.addEventListener('input', event => { output.textContent = (editor.value.match(/\\S+/g) || []).length; }); 
 <textarea id='editor'></textarea> <output id='counter'></output> 

Try this instead,

function wordsCount() {
    var arr = editor.innerText.trim().match(/\S+/g); //use innerText instead
    words.textContent = !arr[0] ? 0 : arr.length;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM