JavaScript 查找英文文章高频单词:基于正则表达式的实现

作者:青柠时间:2026-10-21 23:51:29浏览:318

本文介绍如何利用 JavaScript 的正则表达式功能,统计英文文章中出现频率最高的单词。代码通过 trim、toUpperCase 及正则匹配提取单词,并遍历数组计算各词在全文中的出现次数,最终输出最高频单词及其计数。该方法不区分大小写,适用于基础的文本分析场景。

JavaScript 查找英文文章高频单词:基于正则表达式的实现

以下代码展示了如何使用 JavaScript 查找英文文章中出现频率最高的单词。该单词由 26 个英文字母的大小写组成,程序将输出该单词及其出现的次数,且不区分大小写。实现的核心在于正则表达式的应用。

核心代码实现


function counts(article){
 article = article.trim().toUpperCase();
 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];
 }
 }
 console.log(maxword+" "+max);
}
counts("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;");

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

作者最新文章