Word Counter in javascript



Before writing this post,when i have searched for the word counter in javascript i found so many scripts that are not up to the mark.The script was like below.


function countwords(textarea){
 var words=textarea.split(" ");
 alert(words.length+" words");
}


This script is wrong.You are having question why its wrong?.Because splitting with space is used in the above script.Its not the only thing to separate the words.

A newline will be inserted if there is Return at the end of the word, which won't be counted as a word separator by the above code.commas or other punctuations  which are not followed by a space are also not handled in the above script.Even if you leave a space at the end of the word it will also counted as a word that is totally wrong.

So what could be the right solution for this case? As a solution, in the following script we are using regular expression.The pattern '\w+'used here will match a srting of characters of the word.Using this script you dont need to worry about extra space at the end of the word.

<html>
<head>
<script type="text/javascript">
function wordcount(textarea){
 var chars=textarea.length,
 words=textarea.match(/\w+/g).length;
 document.getElementById('word_count').value=words;
}
</script>
<style type="text/css">
body{
display: inline;
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 160%;
font-style: normal;
font-weight:1024;
color: #68677C;
background-color:#F6F9F9;
}
a{
color: #68677C;
text-decoration:blink;
}
</style>
</head>
<body>
<form name="demoform" method=”post”>
<center>
<div style="margin-top:100px;"><strong><a href="http://php-dev-zone.blogspot.in">PHP Dev Zone</a></strong> - Words Counter Demo<div>

<div style="border:3px solid #7AAB8A;width:480px;height:200px;background-color:#99D6AD;margin-top:20px;">
    <table>
     <tr>
       <td><strong>Enter the Words in the Textarea</strong></td>
     </tr>
    <tr>
       <td colspan="2"><textarea style="background-color: rgb(238, 255, 238); margin: 2px; height: 93px; padding:2px 0 0 2px;" cols="40" onkeyup="wordcount(this.value)" name="texarea"> </textarea>
       </td>
     </tr>
    <tr>
       <td><label style="margin-left:165px;">Words entered :</label></td>
       <td><input type=text name=words id=word_count size=4 readonly ></td>
     </tr>
    </table>
</div>
</center>
</form>
</body>
</html>

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP