Day # 69: Word count
I do not think there is better way to practice the fundamentals of Javascript than by doing things with the DOM. You get to do things and you automatically find out if they’re right or not… by just taking a look at the DOM!
That being said, for today’s project I decided to create a word and character counter. I started by creating a textarea and adding an event listener to an input to determine how many characters and words the user is entering.
To count characters, one can set a very straightforward function like this on Javascript:
inputTextArea.addEventListener("input", () => {
characCount.textContent = inputTextArea.value.length
})
To count words, the function gets rather more complicated. However if we divide this task into a series of steps, then the challenge gets feasible:
1. Split the text separated by spaces into an array of substrings
2. Filter the empty strings
3. Determine the length of this array
These steps are made in these lines of Javascript:
let txt = inputTextArea.value.trim();
wordCount.textContent = txt.split(/\s+/).filter(
(item) => item).length
Comments
Post a Comment