January 1, 2011

In this post, I have demonstrated how to calculate the number of words using both JavaScript and C# code and also how to restrict a TextArea or a multiline TextBox control to contain the specified number of words. One of the challenge in writing this article is to determine what a word is. For the purpose of this post, I have considered any text to be a word that is separated by a space. The words may contain symbols but must contain alphabets. For example, work’s is a word but ;’; is not.

On aspx page, a multiline TextBox control and a span element is first declared. The text to be manipulated will be obtained from the TextBox and the span will display the status. The code is below.

aspx
  1. <asp:TextBox ID="T2" runat="server" TextMode="MultiLine" Rows="3" onkeyup="WordCount()"></asp:TextBox>
  2. <span id="T2Status" style="color:Red;">5 word(s) remaining.</span>

The TextBox contain a KeyUp event. This is a JavaScript event that checks the number of words entered in the TextBox control and updates the status in the span element. The JavaScript code is below.

JavaScript - TextBox max words
  1. <script type="text/javascript">
  2.     function WordCount() {
  3.         var text = document.getElementById('<%= T2.ClientID %>').value;
  4.         var list = text.split(" ");
  5.  
  6.         var x; var upper; var lower;
  7.         var count = 0;
  8.         var max = 5;
  9.  
  10.         //Use the following to count the number of words
  11.         /*for (x in list) {
  12.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  13.                 count = count +1;
  14.             }
  15.         }*/
  16.  
  17.         var val = "";
  18.  
  19.         for (x in list) {
  20.             if (list[x].toUpperCase() != list[x].toLowerCase()) {
  21.                 if (count +1 <= max) {
  22.                     count = count + 1;
  23.                     val += list[x];
  24.                     //alert("val: " + val + " list: " + list[x]);
  25.                 }
  26.             }
  27.             else {
  28.                 if (count <= max) {
  29.                     val += list[x];
  30.                     //alert("val: " + val + " list: " + list[x]);
  31.                 }
  32.             }
  33.             if (x != list.length -1) {
  34.                 val += " ";
  35.             }
  36.         }
  37.  
  38.         document.getElementById('<%= T2.ClientID %>').value = val;
  39.         document.getElementById('T2Status').innerHTML = max - count + " words remaining";
  40.     }
  41.  
  42. </script>

In JavaScript code, I am first getting the string from the TextBox and then splitting it into an array. Then, I am converting each string in the array into both upper and lower case. Then, I am comparing the converted strings. If the string match, it’s a word, otherwise, not. At the same time, I am creating another string based on the values in the array till it hits the max number of words. This string is then used to populate the TextBox.

The same can be achieved using C# code but this will cause unnecessary postbacks to the server. However, it is advisable to check the data using C# to avoid a user submitting the data from a browser with JavaScript disabled.

I have written two methods – one to do a word count and want to limit the string to a maximum number of words. In this first method to do a word count, I have broken the string into a string array using space - “ “ - as the delimiter. Then, I have check if a particular string on the array contains an English letter. If it does, the counter is updated. The code for this method is below.

C# - WordCount() method
  1. private int WordCount(string s)
  2. {
  3.     int c = 0;
  4.     string[] split = {" "};
  5.  
  6.  
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  8.  
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  11.  
  12.  
  13.     string val = string.Empty;
  14.  
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.             c++;                             
  19.     }
  20.  
  21.     return c;
  22. }

In the next method, I have reconstructed a string to limit it to maximum number of words specified. It uses the same logic as to count the number of words. A new string is created based on the values in the string array. The code for the method is below.

C# - String, max words
  1. private string MaxWord(string s, int max)
  2. {
  3.     int c = 0;
  4.     string[] split = { " " };
  5.  
  6.  
  7.     string[] list = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
  8.  
  9.     char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  10.                 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
  11.  
  12.  
  13.     string val = string.Empty;
  14.  
  15.     for (int i = 0; i < list.Count(); i++)
  16.     {
  17.         if (list[i].IndexOfAny(ch) >= 0)
  18.                 c++;
  19.         if (c <= max)
  20.             val += list[i] + " ";
  21.     }
  22.  
  23.     return val;              
  24. }
Reference: Shahed Kazi at AspNetify.com