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).


<title> Demo

function count()
var m=f.t1.value
var k=0
if(m.charAt(i)==" ")
if(m.charAt(i+1)!=" ")
alert("Number of words in the string are: "+k)




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


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:

Comments, or errors are welcome as always! :)

Happy Scripting! ;)

No comments:

Post a Comment

Any Thoughts?