最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Limit words in a textarea - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked Sep 24, 2009 at 0:52 Ben SinclairBen Sinclair 3,9868 gold badges57 silver badges98 bronze badges 1
  • Define word, please. Are these words - "self-contained", "43rd", "café", "курица"? – kangax Commented Sep 24, 2009 at 3:11
Add a comment  | 

9 Answers 9

Reset to default 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(' ');

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.

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.

this well help

function limit_words($post_content, $word_limit=30)
{
$words = explode(" ",$post_content);
return implode(" ",array_splice($words,0,$word_limit));
}
<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>
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);

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.

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>

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)
}
发布评论

评论列表(0)

  1. 暂无评论