限制textarea中的单词 [英] Limit words in a textarea
问题描述
我已经对此进行了一些搜索。发现大量的脚本可以统计字符,甚至可以计算单词,但找不到任何可以删除超过单词限制的单词....
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.
感谢您的帮助!
推荐答案
field.value = field.value.split(' ').splice(0, maxWords).join(' ');
更新
我注意到这也是计算 n
行中的空格为 n-1
单词,由此修复:
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(' ');
这篇关于限制textarea中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!