Count Words In A Sentence

In this article, we are going to learn to Count Words In A Sentence Using JavaScript. This article will allow the user to put a sentence into Textarea and the program will calculate the words in the given sentence then the user clicks the "Count" button to show the result. And, we added a "Clear" button to reset the Textarea to have a new sentence to calculate. HTML Code This HTML code that the users can input their sentence to count how many words all in all.
  1. <h2>Count Words in a Sentence</h2>
  2.  
  3. <br />
  4. <textarea cols="40" class="insert_sentence" id="insertContent" autofocus="autofocus"></textarea>
  5. <br />
  6. <br />
  7. <input type="submit" class="btn_control" value="Count" onclick="count_words()" />    
  8. <input type="submit" class="btn_control1" value="Clear" onclick="clear_textbox()" />
  9. <br />
  10. <br />
  11. <br />
  12.  
  13. <p id="result" class="text_result"></p>
JavaScript This script uses to count those words in a sentence.
  1. <script type="text/javascript">
  2. function count_words() {
  3.         var input = document.getElementById("insertContent").value;
  4.         var number = parseInt(input);
  5.         count_word=input.split(" ")
  6.         document.getElementById("result").innerHTML =
  7.         "Number of words in your sentence is <b style='color:blue; font-size:23px;'>" +
  8.         count_word.length + "</b>.";
  9.  }
  10. function clear_textbox(){
  11.         document.getElementById("result").innerHTML = "";
  12.         document.getElementById("insertContent").value="";
  13.         document.getElementById("insertContent").focus();
  14. }
  15. </script>
And, this is the style.
  1. <style type="text/css">
  2. body {
  3.         width:300px;
  4.         margin:auto;
  5. }
  6. .insert_sentence {
  7.         border:blue 1px solid;
  8.         background:azure;
  9.         font-size:large;
  10.         font-family:Helvitica;
  11.         padding:10px;
  12. }
  13. .btn_control {
  14.         font-size:18px;
  15.         border:blue 1px solid;
  16.         color:blue;
  17.         background:skyblue;
  18.         padding:5px;
  19.         margin-right:20px;
  20.         border-radius:8px;
  21.         cursor:pointer;
  22. }
  23. .btn_control1 {
  24.         font-size:18px;
  25.         border:blue 1px solid;
  26.         color:blue;
  27.         background:white;
  28.         border-radius:8px;
  29.         padding:5px;
  30.         cursor:pointer;
  31. }
  32. .text_result {
  33.         width:300px;
  34.         font-size:18px;
  35.         color:red;
  36.         border:blue 1px solid;
  37.         background:white;
  38.         padding:50px;
  39. }
  40. h2 {
  41.         color:blue;
  42. }
  43. </style>
So what can you say about this work? Share your thoughts in the comment section below or email me at [email protected]. Practice Coding. Thank you very much.

Add new comment