当前位置:   article > 正文

JavaScript 获取指定字符串中出现次数最多的单词及其出现次数_js统计出现最多的单词 go to the vineyard in the west. there

js统计出现最多的单词 go to the vineyard in the west. there are many vines in

还记得我之前有篇博客讲的如何用JavaScript 获取指定字符串中出现次数最多的字符及其出现次数吗?这次是找单词哦!上代码:

let article = "Age has reached the end of the beginning of a word. May be guilty in his seems to passing a lot of different life became the appearance of the same day;";
function findMostWord(article){
	//使用trim()方法删除字符串的头尾空白符
	article = article.trim();
	//利用正则取出所有单词存放于数组中
    var array = article.match(/[A-z]+/g);
	//所有单词以空格间隔重新拼接
    article = " " + array.join(" ") + " ";
    var max = 0,word,num = 0,maxword = "";
	//遍历拼接成的新字符串
    for(var i = 0; i < array.length; i++) {        
        //将所有的单词作为匹配项
		word = new RegExp(" " + array[i] + " ",'g');
		//相当于是统计每个单词的次数
		num = article.match(word).length;
		//比较所有单词出现次数
		if(num > max){
			max = num;
			maxword = array[i];
		}
   }
   return {maxword,max}
}
console.log(findMostWord(article));
//打印结果:{ maxword: 'the', max: 4 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

但是遗憾的是这个方法没有考虑到同时有多个单词出现次数最多的情况。后续想到解决方案再更新吧。。。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/527257
推荐阅读
相关标签
  

闽ICP备14008679号