我正在尝试在文本框中实现单词计数器。我正在使用以下链接:
JS Fiddle
Second link
<textarea name="myMessage" onkeyup="wordcount(this.value)"></textarea>
<script type=""text/javascript"">
var cnt;
function wordcount(count) {
var words = count.split(/\s/);
cnt = words.length;
var ele = document.getElementById('w_count');
ele.value = cnt;
}
document.write("<input type=text id=w_count size=4 readonly>");
</script>
文字计数器工作正常。但是我的情况如下:
对于单词“最合适的匹配项”,如果用户键入缩写形式为“ MSM”,则MSM也应计为3个单词。
同样,如果有大学名称,如“ DAV”,则也应计为3个单词。
请建议!
最佳答案
我有一个简单的功能:
var regex = [/DAV/g, /MAC/g];
function countWords() {
var count = [];
regex.forEach(function(reg) {
var m = text.match(reg);
if (m) {
count = count.concat(m);
}
});
// the number of known acronym wrote in the text
var acronyms = count.length;
// how much words generated from an acronym (e.g. DAV === 3 words; AB === 2 words and so on)
var wordsFromAcronyms = count.join().replace(/,/g,'').length;
// how many words wrote (this is equal to your code)
var rawWords = text.match(/\S+/g).length;
// compute the real number
return rawWords - acronyms + wordsFromAcronyms;
}
它计算写出的首字母缩写词的数量(已知首字母缩写词的列表存储在
regex
数组中),然后计算首字母缩写词(wordsFromAcronym
)生成多少个单词,然后减去首字母缩写词的数量(),从总单词(acronyms
)中添加,然后添加rawWords
。这是PLNKR。