Developing a JavaScript Word Counter

avatar
(Edited)

Hello devs!
Lately, I've been making use of some online word counters and I can say they really do come in handy.
Word counters help you to ensure the number of words or characters in your write-up meets a certain requirement or does not exceed a certain limit.
Even when writing posts here on hive, we always get to see the word count.

I became really curious about how word counters are programmed to function in browsers, so I decided to challenge myself and I was able to build mine using JavaScript.

And I'll be sharing my very own
tutorial on building a simple JavaScript word counter🙂.

First of all, we start with defining the structure of our Word Counter page with a little HTML code.
Most importantly, we would be including the textarea tags which is where the words will be typed into. Also, a div at the top which would show the word count.

<!DOCTYPE html>

<html lang="eng" >

<head>

      <meta charset="UTF-8" >
      <meta name="viewport" content="width=device-width, initial-scale=1" >

      <title>Charles Word Counter</title>

</head>

<body>

    <div class="cont" >
          <div id="display" ></div>
          <textarea id="text" ></textarea>
    </div>

</body>
</html>

The outcome:

Then we move on to styling up the contents of our page with CSS. Here we specify the position, width, background colors, fonts and so on.

body {
background: #006;
}

.cont {
position: absolute;
top: 10%;
left: 50%;
translate: -50%;
width: 90%;
height: 50%;
}

#text {
box-sizing: border-box;
outline: none;
width: 100%;
height: 100%;
padding: 1.5em 1em;
font: normal  500 0.9em/1.6em serif;
background: #eee;
color: #000;
brder: 1px solid #fff;
border-radius:  5px;
}

#display {
font:  normal 900 1.8em sans-serif;
margin:  0.5em 0;
color:  #eee;
}

Now let's see how it turns out :

That's much better 🙂

Now that we've gotten the structure all set up, let's work on getting it to function.
We're going to program it to automatically count both the words and characters in what ever chunk of text we type in the textarea field and continuously display the results in the div we fixed above the textarea.

Firstly, let's create the function which would be doing the counting.
We start by declaring and naming it :

function wordCounter() {

}

Now we use the simple code to access the textarea value and store it in the variable text and also access the div (which would be displaying the count ) and store it in the display variable :

  let text = document.getElementById("text").value;
  let display = document.getElementById("display");

Since the value gotten from the textarea input field will be in the form of a string, we need to convert it to array form in order to do the counting efficiency.
Let's work on counting the words first.

  let arr1 = text.replace(/\n/g, " " ).trim().split( " " );

The replace() method would replace all line breaks in the string with single space characters.
The trim() method would remove whitespace from both sides of the string.
And finally, the split() method would split the string at the spaces and return an array of all the words.
Now we have created arr1.

To count the words, let's make use of loops.
First, we initialize the word count by setting it to zero, then we loop through arr1 and increase the word count when each split word is not empty.

 let wordCount = 0 ;
  for(let i = 0; i < arr1.length ; i++){
    if(arr1[i] != "" ) {
      wordCount += 1 ;
    }
  }

At the end of the loop the wordCount variable would store the number of words in the textarea.

Now let's work on counting the characters.
We also need to create a new array.

let arr2 = text.replace(/\n/g, "" ).split( "" );

Now arr2 has been created.
It's actually a bit similar to arr1 but in this case, the replace() method would replace all line breaks with empty strings ( "" ) and the split() method would return an array of all the characters in the textarea field, including the spaces.
We won't be executing the trim() method here because white spaces are also considered as characters.

We're also going to make use of loops to count the characters.
Let's start by initializing the character count by setting it to zero, then we loop through arr2 and increase the character count after each successful loop.

let arr2 = text.replace(/\n/g, "" ).split( "" );
  let charCount = 0 ;
  for(let i = 0; i < arr2.length; i++){
    charCount += 1 ;
  }

At the end of the loop, the total number of characters found in the textarea field would be stored in the charCount variable.

And now to display the count results, let's make use of template literals :

display.innerHTML = `${wordCount} words ${charCount} characters`;

This code will display the results in the div which we have already accessed and stored in the display variable.

Now we've successfully built up the function. Let's see the full JavaScript code.

function wordCounter() {
  let text = document.getElementById("text").value;
  let display = document.getElementById("display");
  
  let wordCount = 0 ;
  let arr1 = text.replace(/\n/g, " " ).trim().split( " " );
  for(let i = 0; i < arr1.length ; i++){
    if(arr1[i] != ""){
      wordCount += 1 ;
    }
  }
  
  let arr2 = text.replace(/\n/g, ""b).split( "" );
  let charCount = 0 ;
  for(let i = 0; i < arr2.length; i++){
    charCount += 1 ;
  }
  
  display.innerHTML = `${wordCount} words ${charCount} characters` ;
}

We must also not forget to use setInterval() to continuously call the function so that the results can be automatically updated as words are typed in.

setInterval(wordCounter);

Now let's test it out!🙂

It works perfectly🙂!

This project had me doing a lot of thinking and it took me quite some time to come up with the best approach. There were so many failed attemps but I'm glad I was able to figure it out and I really look forward to learning and doing more stuff with JavaScript.

I would love to hear your opinions! 😊

Thanks for reading!❤️



0
0
0.000
4 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000
avatar

Congratulations @charlrific! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You received more than 2000 upvotes.
Your next target is to reach 2250 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Our Hive Power Delegations to the September PUM Winners
Feedback from the October 1st Hive Power Up Day
Hive Power Up Month Challenge 2022-09 - Winners List
Support the HiveBuzz project. Vote for our proposal!
0
0
0.000
avatar

Just wow! I'm impressed by how well you know JavaScript, you were able to explain this tutorial very well and anybody with a basic understanding of JavaScript can easily follow along. I am looking at some of the codes and I can see there are different ways to approach them, I will experiment with this later on

0
0
0.000
avatar

Thanks a lot bro!
I had to try so many methods but most of them had drawbacks. It took me a lot of time but I eventually arrived at this one.
Thanks for reading!

0
0
0.000