Reputation: 13616
I created this application. The program counts the number of the words in the text.
But I have bug when I print first character (any character) it taken as a word, I can't understand why.
Here is jQuery:
counter = function () {
var value = $('#text').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
//var regex1 = /[^A-Za-z_]/gim;
var regex1 = /[^a-z_]/gim;
var regex2 = /\s+/gi;
var textTrimmed = value.replace(regex1, '');
var wordCount = textTrimmed.trim().replace(regex2, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex1, '').length;
$('#textFiltered').html(textTrimmed.trim().replace(regex2, ' '));
$('#textTrimmed').html(textTrimmed);
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function () {
$('#count').click(counter);
$('#text').change(counter);
$('#text').keydown(counter);
$('#text').keypress(counter);
$('#text').keyup(counter);
$('#text').blur(counter);
$('#text').focus(counter);
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Copy & Paste, Word & Character counter</title>
</head>
<body>
<div id="border">
<textarea id='text'></textarea>
</div>
<button id="count">Count</button>
<div id="result">
Words: <span id="wordCount">0</span><br/>
Total Characters(including trails): <span id="totalChars">0</span><br/>
Characters (excluding trails): <span id="charCount">0</span><br/>
Characters (excluding all spaces): <span id="charCountNoSpace">0</span>
</div>
</body>
</html>
How can I fix the bug?
Upvotes: 1
Views: 78
Reputation: 1456
If the issue is that you don't want any character to be counted as a word till it's completed, then you can check for existence of ' ' before displaying it as count
Add this line of code to after initializing wordCount variable
if (textTrimmed.replace(regex2, ' ').indexOf(' ') < 0)
wordCount = 0;
Refer: http://jsfiddle.net/54v67r36/
Apart from this, your fiddle wasn't counting as the regex expressions were not in quotes (refer my comments) - although your actual counter wasn't having this issue
Upvotes: 1
Reputation: 1638
Your question is not very clear but from what I understand I think the problem is in the below line
var wordCount = textTrimmed.trim().replace(regex2, ' ').split(' ').length;
change it to this
var wordCount = value.trim().split(' ').length;
Upvotes: 2