How to count words using JQuery
In this tutorial, we are going to see how to count words using JQuery. You can calculate or find the number of words in a string using JavaScript’s split() method. This method simply splits a string into an array of substrings based on a specified character.
In the following example, we also used the trim() method to remove white space at the start/end of a specified string before counting the number of words.
How to count words using JQuery
<!DOCTYPE html> <html> <head> <title>How to count words using JQuery</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ var words = $.trim($("textarea").val()).split(" "); alert(words.length); }); }); </script> </head> <body> <textarea style="width: 450px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</textarea> <button type="button">Count words</button> </body> </html>
Result |
---|
|