Skip to content

Instantly share code, notes, and snippets.

@savicas
Created October 24, 2019 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savicas/38c2cc7d1e7d7f99e81592bb2be6a9fb to your computer and use it in GitHub Desktop.
Save savicas/38c2cc7d1e7d7f99e81592bb2be6a9fb to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<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%;
}
</style>
</head>
<body>
<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>
<script>
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(text.value);
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);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment