miguelslp - Vanilla JS

Character and Word Count

You've written 0 words and 0 characters.

<label for="text">Enter your text below.</label>
<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>
<script async>

// Variables
let textArea = document.querySelector('textarea');
let charCounter = document.querySelector('#character-count');
let wordCounter = document.querySelector('#word-count');

// Methods
function handleInput(inputElement, countElement, wordCountElement) {
let newArray = inputElement.value.split(/\s+/).filter(function (item) {
return item != '';
})
countElement.textContent = newArray.join('').length;
wordCountElement.textContent = newArray.length;
}

// Listeners
textArea.addEventListener('input', function () {
handleInput(this, charCounter, wordCounter);
});

</script>