我想运行一个脚本来计算文本区域中的单词,其中不包括所有单字母单词。因此,如果有人输入句子“ This is a word count”,我希望该计数为4,因为它排除了“ a”。
我具有基本的jQuery知识,但能够获得包括单字母单词在内的单词计数:
var wordCounts = {};
jQuery("#65").keyup(function() {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
jQuery.each(wordCounts, function(k, v) {
finalCount += v;
});
console.log(wordCounts);
}).keyup();
我是否想做类似的事情
if (matches.length >= 2) {
finalCount += v;
}
我似乎找不到任何可以做到这一点的东西,这很简单,请帮助:)
您可以通过将正则表达式修改为\b\w{2,}
来避免单个字母的单词。这将查找单词边界,然后是2个字符或更长的单词。
var wordCounts = {};
jQuery("#65").on('input', function() {
var matches = this.value.match(/\b\w{2,}/g).length;
wordCounts[this.id] = matches;
console.log(wordCounts);
}).trigger('input');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="65">This is a word count</textarea>
也请注意,事件处理程序中的each()
循环是多余的,因为id
仅会选择一个元素。如果您希望此方法适用于多个元素,请对它们全部使用一个通用类:
$(".count").on('input', function() {
console.log(getWordCounts());
});
function getWordCounts() {
let wordCounts = {};
$('.count').each((i, el) => wordCounts[el.id] = el.value.match(/\b\w{2,}/g).length);
return wordCounts;
}
console.log(getWordCounts());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="65" class="count">This is a word count</textarea>
<textarea id="foo" class="count">Lorem ipsum dolor sit amet consectetur adipiscing elit</textarea>