我用这个提取字数:
var sim = /\s+/gi;
var words= parag.value.trim().replace(sim, ' ').split(' ').length;
我想显示重复的单词,我该怎么做?
最佳答案
以下代码片段将为您提供文本中重复单词的数组:
var text = "this is this and that was that";
var frequency = text.split(' ').reduce(function(previous, current) {
if (!previous.hasOwnProperty(current)) {
previous[current] = 0;
}
previous[current] += 1;
return previous;
}, {});
var repeatedWords = Object.keys(frequency).filter(function(element) {
return frequency[element] > 1;
});
console.log(repeatedWords);
// => ["this", "that"]
- 将文本拆分为标记。
- 将数组缩减为对象。
- 初始化一个空对象。
- 如果 token 不存在,则将其设置为 0。
- 将 token 计数增加 1。
- 检查每个标记。
- 过滤计数大于 1 的 token 。
关于javascript - 显示文本区域中重复的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076588/