JavaScript 获取指定字符串中出现次数最多的单词及其出现次数

还记得我之前有篇博客讲的如何用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 }

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值