Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
<!DOCTYPE html>
<title>Character & Word Count</title>
<style type="text/css">
body {
margin: 1em auto;
max-width: 40em;
width: 88%;
label {
display: block;
width: 100%;
textarea {
min-height: 24em;
width: 100%;
<h1>Character & Word Count</h1>
<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>
const text = document.querySelector('#text');
const charCount = document.querySelector('#character-count');
const wordCount = document.querySelector('#word-count');
const regex = /[\n\r\s]+/g;
\r matches Carriage return
\s matches any whitespace character: spaces, tabs, newlines and Unicode spaces
\n matches a newline character
g matches a global match.
//Listen the event for any change
text.addEventListener('input', function (event) {
const words = text.value.split(regex).filter(function (word) {
return word.length > 0;
/* checking the info that we're looking for:
console.log('this is charLength: '+ text.value.length);
console.log('wordsLength: ' + wordCount.textContent);
console.log('words value is ' + words.length);
//counting and displaying number of words
wordCount.textContent = words.length;
//Counting and displaying number of chars
charCount.textContent = text.value.length;
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment