05. Character and Word Count


You've written 0 words and 0 characters.

HTML

1
2
3
4
<label class="label" for="text">Enter your text below.</label>
<textarea class="textarea" id="text"></textarea>

<p>You've written <strong><span id="word-count">0</span> words</strong> and <strong><span id="character-count">0</span> characters</strong>.</p>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* As the user types or pastes content in, the text of the #word-count
and #character-count elements should be updated to show how many words
and characters are in the #text field. */

const textArea = document.querySelector('#text');
const countCharOutput = document.querySelector('#character-count');
const countWordOutput = document.querySelector('#word-count');

function counter() {
const wordsArr = textArea.value.split(/[\n\r\s]+/g).filter(item => {
return item.length > 0;
});
countCharOutput.textContent = textArea.value.length;
countWordOutput.textContent = wordsArr.length;
};

textArea.addEventListener('input', counter);