Reputation: 381
here is the script for counting words.
HTML Message: Total word Count : 0 words.
jquery
$(document).ready(function () {
$('#word_count').wordCount();
});
jQuery.fn.wordCount = function (params) {
var p = {
counterElement: "display_count"
};
var total_words;
if (params) {
jQuery.extend(p, params);
}
//for each keypress function on text areas
this.keypress(function () {
total_words = this.value.split(/[\s\.\?]+/).length;
jQuery('#' + p.counterElement).html(total_words);
});
};
fiddle http://jsfiddle.net/ZmbxS/
Upvotes: 1
Views: 317
Reputation: 318182
Can it be made simple?
sure can, use a word boundary matching anything that isn't whitespace :
$('#word_count').on('keyup', function() {
$('#display_count').text(this.value.split(/\b\S+\b/g).length-1)
});
and it seems like a wasted use of a plugin for something that can be done that easily ?
Upvotes: 6
Reputation: 10003
See this:
You need to "trim" your value to ensure that there are no leading/trailing spaces (which produce mentioned +1)
I've attached this handler to keyup
event instead.
Code:
this.keyup(function () {
my_value = this.value.replace(/^\s+|\s+$/, '');
total_words = my_value.split(/[\s\.\?]+/).length;
jQuery('#' + p.counterElement).html(total_words);
});
Upvotes: 0
Reputation: 699
I think it is a matter on the event you're using. I'd suggest you to bind the function to the change event.
For the regexp, it is not enough to make the split just by?:
stringValue.split(/\s/);
Best regards.
Upvotes: -1