How to calculate the number of words in a string using JQuery?

In order to calculate the number of words in a string, we can Use the JQuery split() method along with or without trim() method.
.split() method simply split a string into an array of substrings by a specified character and .trim() method to remove the leading and trailing white spaces.

Syntax:

string.split(separator, limit)
    Approach:

  • Get the string from the HTML element.
  • Split the string into substring on the basis of whitespaces.
  • Count the number of substrings.

Example 1: Along with trim() method, removing starting and ending spaces from the string




<!DOCTYPE html>
<html>
  
<head>
    <title>How to calculate the number 
      of words in a string using Javascript?</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js">
  </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;"
        w3wiki 
    </h1>
    <h3>How to calculate the number of words
      in a string using Javascript?</h3>
    <textarea> Beginner For Beginner </textarea>
    <br>
    <button type="button">Click</button>
    <script type="text/javascript">
        $(document).ready(function() {
            $("button").click(function() {
                // reduce the whitespace from both sides of a string. 
                var Beginner1 = $.trim($("textarea").val());
                //split a string into an array of substrings
                var geek = Beginner1.split(" ")
                    // count number of elements
                alert(geek.length);
            });
        });
    </script>
</body>
  
</html>


Output:

  • Before Click on button:
  • After Click on button:

Example 2: Without trim() method




<!DOCTYPE html>
<html>
  
<head>
    <title>Calculate the number
      of Words in a String</title>
  
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;"
        w3wiki 
    </h1>
    <h3>How to calculate the number of
      words in a string using Javascript?</h3>
    <p id="Beginner1"></p>
    <br>
    <button onclick="myFunction()">Click</button>
    <p id="Beginner"></p>
  
    <script>
        var str = "Beginner For Beginner";
        document.getElementById("Beginner1").innerHTML = str;
  
        function myFunction() {
            var res = str.split(" ");
            document.getElementById(
              "Beginner").innerHTML = res.length;
        }
    </script>
</body>
  
</html>


Output:

  • Before Click on button:
  • After Click on button: