5

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!

Ben Sinclair
  • 3,896
  • 7
  • 54
  • 94
  • **Define word**, please. Are these words - "self-contained", "43rd", "café", "курица"? – kangax Sep 24 '09 at 03:11

9 Answers9

4
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
  • 97,545
  • 26
  • 194
  • 236
4

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
  • 643,351
  • 109
  • 780
  • 844
4

jQuery Simply Countable plugin
Provides a character or word counter (and limiter) for any text input or textarea. Works when typing or pasting text.

@version 0.4.2
@homepage http://github.com/aaronrussell/jquery-simply-countable/
@author Aaron Russell http://www.aaronrussell.co.uk

Copyright (c) 2009-2010 Aaron Russell
Dual licensed under the MIT http://www.opensource.org/licenses/mit-license.php
and GPL http://www.opensource.org/licenses/gpl-license.php licenses.

Chris Jacob
  • 11,878
  • 7
  • 47
  • 42
2

this well help

function limit_words($post_content, $word_limit=30)
{
$words = explode(" ",$post_content);
return implode(" ",array_splice($words,0,$word_limit));
}
sourabh kasliwal
  • 947
  • 3
  • 8
  • 21
1
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}
</script>
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
lsmeera
  • 11
  • 1
0
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
  • 102,654
  • 32
  • 106
  • 127
0

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.

0

I did it like this

function limitWord(myString, limit){
 return myString
  .replace(/\s+/g, ' ') // remove extra spaces between words
  .split(' ')           // split string into array (using spaces as seperator)
  .splice(0, limit)     // splice the array to the desired word limit
  .join(' ');           // join it back into string (using spaces as seperator)
}
Jason J. Nathan
  • 7,422
  • 2
  • 26
  • 37
  • This answer has been flagged for quality review due to its length. SO prefers answers with some text explaining how this code solves the OP's problem. Please read [answer]. Thanks. – Software Engineer Oct 09 '14 at 15:35
  • better now @EngineerDollery? – Jason J. Nathan Oct 09 '14 at 17:39
  • Personally, I think the solution was simple enough that it didn't need a lot of verbage. But, it was flagged, and unfortunately it'll get flagged again. I think the flagging system looks at the balance of text to code, and you've made the code even longer so your balance is even more skewed. – Software Engineer Oct 09 '14 at 18:14
  • I have answered posts like that before. Barely any text. http://stackoverflow.com/a/14731922/382536 – Jason J. Nathan Oct 09 '14 at 18:44
  • Like I said, it's not me flagging these answers, it's the SO system. I'm not sure on the algorithm, so high vote posts may not get flagged at all. If you read the [answer] post you'll see what I mean. – Software Engineer Oct 09 '14 at 19:06
  • Of course, @EngineerDollery. Haha. I'm just saying :) – Jason J. Nathan Oct 10 '14 at 12:25
0

This function will limit, and allow no more words:

function limitWords(id) {
    var maxWords=5;
    var d=document.getElementById(id);
    if ( d.value.split(' ').length > maxWords ) {
        t=d.value.substring(0,d.value.lastIndexOf(' '));
        d.value=t.substring(0,t.lastIndexOf(' ')+1);
    }
}

Example HTML

<textarea id='txt' rows="2" onkeyup="limitWords(this.id)"></textarea>
Owen
  • 7,347
  • 12
  • 54
  • 73