I've done a bit of searching on this. Found plenty of scripts that counted characters and even counted words but couldn't find one that removes any words that go over the word limit....
Here is my script so far...:
var maxWords = 10;
function countWordsLeft(field) {
totalWords = field.value.split(' ');
if (totalWords.length > maxWords)
field.value = field.value.substring(0, maxWords);
else
document.getElementById('description_count').innerHTML = maxWords - totalWords.length;
}
I've got the following line which I copied from a character count script but obviously this wont work because I am counting words
if (totalWords.length > maxWords)
field.value = field.value.substring(0, maxWords);
How do I make the script delete any extra words added over the limit? I need this especially if they paste in a description... It needs to count the words and then delete any words over the limit.
Appreciate your help!
field.value = field.value.split(' ').splice(0, maxWords).join(' ');
update
I noticed that this also counts n
spaces in a row as n-1
words, which is fixed by this:
var a = field.value.split(' ');
var words=0, i=0;
for(; (i<a.length) && (words<maxWords); ++i)
if(a[i].length) ++words;
field.value = a.splice(0,i).join(' ');
I would probably use this:
var maxWords = 10;
function limitLengthInWords(field) {
var value = field.value,
wordCount = value.split(/\S+/).length - 1,
re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0,"+(maxWords-1)+"}");
if (wordCount >= maxWords) {
field.value = value.match(re);
}
document.getElementById('description_count').innerHTML = maxWords - wordCount;
}
This will preserve the whitespace at the begin and between the words.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With