Using keyup is a bit late, as the key has already been pressed:
$('#test').keypress(function(e){
var v = $(this).val(),
w = v.split(/\b[\s,\.-:;]*/),
word = 'img',
c = 0;
for (var i=0,len=w.length;i<len;i++){
if (w[i] === word){
c++;
}
}
if(c == 3){
return false
}
$('#output').text(c);
});
Here's an easier way:
$('#test').on('keypress', function(e){
var word = 'img',
count = this.value.match(new RegExp('\\b'+word+'\\b','g')) || [];
$('#output').text(count.length);
return count.length < 3;
});
EDIT:
As a requirement seems to be to be able to use backspace, keypress can't be used as it doesn't register backspace.
However, keydown will, and with some clever magic we can do:
$('#test').on('keydown', function(e){
var word = 'img',
count = this.value.match(new RegExp('\\b'+word+'\\b','g')) || [];
$('#output').text(count.length);
return !(count.length > 2 && e.which != 8); // 8 is backspace
});