Q:

How to calculate the number of words in a string using jQuery

0

How to calculate the number of words in a string using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JavaScript split() method

You can calculate or find the number of words in a string using the JavaScript split() method. This method simply split a string into an array of substrings by a specified character.

In the following example we have also used the trim() method to remove the leading and trailing white spaces from the string before counting the numbers of words.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Count Number of Words in a String</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            var words = $.trim($("textarea").val()).split(" ");
            alert(words.length);
        });
    });
</script>
</head>
<body>
    <textarea cols="50">The quick brown fox jumps over the lazy dog.</textarea>
    <br>
    <button type="button">Count Words</button>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to find substring between the two words using ... >>
<< How to get the current page url using jQuery...