还记得我之前有篇博客讲的如何用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 }
但是遗憾的是这个方法没有考虑到同时有多个单词出现次数最多的情况。后续想到解决方案再更新吧。。。