tags:

views:

231

answers:

4

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!

+3  A: 
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(' ');
Georg Fritzsche
A: 
function wordlimit(s, n){
 var rx= RegExp('([a-zA-Z]+\\S+\\s+){'+n+'}','g'); 
 while(rx.test(s)){
  return s.substring(0, rx.lastIndex);
 }
 return s;
}

//test

s= 'the quick red fox jumps over the lazy brown dog\'s back';
alert(wordlimit(s, 8));

// field.value=wordlimit(field.value,8);

kennebec
A: 

Or you could do something like:

function truncateStringToMaxWords(string, maxWords)
{
  var whitespace = string.match(/\s+/g);
  var words = string.split(/\s+/);

  var finished = [];
  for(var i = 0; i < maxWords && words.length > 0; i++)
  {
    if (words[0] == "") { i--; }
    finished.push(words.shift());
    finished.push(whitespace.shift());
  }
  return finished.join('');  
}
field.value = truncateStringToMaxWords(field.value, 5);

Which would keep your whitespace intact.

Taylor Hughes
A: 

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.

Gumbo