Getting The Count Of Words And Characters In A Text Using JavaScript

With the below code, when we enter some text in an textbox and click button, we will get the count of words and characters in the text entered. 
  1. <input type="text" id="txtinput" />  
  2. <button onclick="countwords()">  
  3.         Check Count</button>  
  4. <script>  
  5.         function countwords() {  
  6.             var val = document.getElementById("txtinput").value;  
  7.             var words = 0, chars = 0;  
  8.             if (val != "") {  
  9.                 words = val.replace(/\s+/gi, ' ').split(' ').length; // Count words  
  10.                 chars = val.length;                                 // Count characters  
  11.             }  
  12.             alert(chars + " Characters & " + words + " Words!");  
  13.         }  
  14. </script>