I just made a word counter using Javascript. Started it of as a jsfiddle attempt out of boredom. Thought it will help me count the words in assignments. blah. I have also made the source code available in github.
The counter is a simple javascript function, but have used jQuery selectors for simplicity and easiness. Initially my aim was to just get the count of words in the textarea by splitting the spaces and adding 1. But that approach is not accurate, when there are multiple spaces between words. So I used regular expression for replacing multiple spaces with a single space: /\s+/gi.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
counter = function() {
var value = $('#text').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
|
The results are set in <span> elements as follows:
1
2
3
4
|
<span id="wordCount">0</span>
<span id="totalChars">0</span>
<span id="charCount">0</span>
<span id="charCountNoSpace">0</span>
|
Now attach the counter function to change, keydown, keypress, keyup, blur and focus events of the textarea, to make sure the function called on every change.
1
2
3
4
5
6
7
8
|
$(document).ready(function() {
$('#text').change(counter);
$('#text').keydown(counter);
$('#text').keypress(counter);
$('#text').keyup(counter);
$('#text').blur(counter);
$('#text').focus(counter);
});
|
This can be accessed in the following links
Please report any bugs, issues or suggestions in github or just comment here.
Share it if you liked!