Monday, May 21, 2012

Program/Script in JavaScript to count the number of words in a String

JavaScript + HTML is a powerful, useful combination. Here I am writing a program combining both, which helps in counting the number of words in a string given by the user.

I just googled about this program but found the top results to be faulty. If one puts more than one space in between two words, the counter counts the number of words to be 3. This is something one should plug in such programs to make it fault-free. I have my own program which does the same without counting more than one consecutive spaces, which I think I should share in case it may be helpful to anyone, although its easy.

Just a simple if() conditional statement can correct this error. This wont count consecutive spaces.

To directly see the demo of this, visit here.

We will use charAt, for loop, and if statements.

Below is the code of the program to count the number of words in a sentence (string).


<html>

<head>
<title> Demo
</title>


<script>
function count()
{
var m=f.t1.value
var k=0
for(i=0;i<350;i++)
{
if(m.charAt(i)==" ")
{
if(m.charAt(i+1)!=" ")
k++
}
}
k=k+1
alert("Number of words in the string are: "+k)

}
</script>

</head>

<body>

<form name="f">
<textarea name="t1" cols="50" rows="4">Enter the text</textarea>
<br>
<input type="button" value="Count" onClick="countWords();">
</form>

</body>
</html>


This code will generate an alert box on the screen telling the number of words in the statement to the user.

The demo of the above code is here:
http://dreamingcub.blogspot.in/p/sample-program-demonstrating-counting.html


Comments, or errors are welcome as always! :)

Happy Scripting! ;)

No comments:

Post a Comment

Any Thoughts?