Created
October 24, 2019 10:41
-
-
Save savicas/38c2cc7d1e7d7f99e81592bb2be6a9fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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