Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit words in a textarea

Tags:

javascript

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!

like image 527
Ben Sinclair Avatar asked Sep 24 '09 00:09

Ben Sinclair


2 Answers

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(' ');
like image 123
Georg Fritzsche Avatar answered Sep 22 '22 13:09

Georg Fritzsche


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.

like image 37
Gumbo Avatar answered Sep 24 '22 13:09

Gumbo