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 >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< h3 >How to calculate the number of words
in a string using Javascript?</ h3 >
< textarea > Geeks For GEEKS </ 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 geeks1 = $.trim($("textarea").val());
//split a string into an array of substrings
var geek = geeks1.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;" >
GeeksForGeeks
</ h1 >
< h3 >How to calculate the number of
words in a string using Javascript?</ h3 >
< p id = "geeks1" ></ p >
< br >
< button onclick = "myFunction()" >Click</ button >
< p id = "geeks" ></ p >
< script >
var str = "Geeks For Geeks";
document.getElementById("geeks1").innerHTML = str;
function myFunction() {
var res = str.split(" ");
document.getElementById(
"geeks").innerHTML = res.length;
}
</ script >
</ body >
</ html >
|
Output:
- Before Click on button:
- After Click on button:
Last Updated :
06 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...