• Register

When we offer a text area it may be the case that we have a limit of the characters to be entered. In this case, it would be good to offer the user the number of characters that have been inserted, and in passing the words.

The first thing we are going to do is create a text area in HTML using the TEXTAREA element.

Inside the form, we include a button, which when pressed will invoke the wordCount () method, which contains all the code of the example to count characters and words in JavaScript.

Inside the wordCount method, the first thing to do will be to get the text from the text area (save redundancy). We will do this through the getElementById method.

textArea = document.getElementById ("area"). value;

Once we have the text, we obtain the number of characters through its length (length property).

numberCharacters = text.length;

The next thing is to count the words that the text has. In order to do this, we will use the split function which TRACES a string into substrings taking as a cut character the one we pass as a parameter, and leaving the result in an array of words.

DividedAreaText = TextArea.split ("");
numberWords = textAreaDivided.length;

The most normal thing is to think that counting the length of the array of words we will have the solution. But there are some cases that we must consider:

  1. That there is a blank at the beginning of the text.
  2. That there is a blank at the end of the text.
  3. That there are several targets in a row.

In the first two cases what we will have to do is eliminate the blank spaces and in the third case, we will have to reduce the X blanks by just one. Things would be easier if we had functions like trim, ltrim or rtrim. But in JavaScript, this is not the case.

To solve this we must resort to regular expressions and the replace function. We must create regular expressions that simulate the exceptions and apply replace (for nothing in the first and second case and for a space in the third case).

The regular expressions that simulate the exceptions are:

firstBlank = / ^ /
lastBlank = / $ /
severalWhites = / [] + / g

Once the exceptions are applied to the text, we will split and count the length.

text = text.replace (severalBlanks, "");
text = text.replace (firstBlank, "");
text = text.replace (lastBlank, "");
TextSplit = text.split (text, "");
numberWords = StrippedText.length;

The order of execution for the elimination of targets will be several targets, first target and last target. Since if we execute several Blancos at the end we can have a beginning or end of the chain with several blank spaces that we do not control.

37,120 points
11 5 4