javascript查找并输出英语文章出现最多次数单词,和英语字符中出现最多字母

  1. 查找出一篇英语文章中出现最多的单词和次数
let article = "  like a my like he me me a a me   ";
let newArticle = article.trim();
let match = newArticle.match(/[a-zA-Z]+/ig);
let wordLength, word, max = 0, maxWord = [];
for (let i = 0; i < match.length; i++) {
  word = new RegExp("" + match[i] + "", 'g');
  wordLength = article.match(word).length;
  if (wordLength == max) {
    max = wordLength;
    maxWord.push(match[i]);
  } else if (wordLength > max) {
    max = wordLength;
    maxWord = [];
    maxWord[0] = match[i];
  }
}
maxWord = [...new Set([...maxWord])];
console.log(`出现次数最多的单词是:${maxWord},次数为:${max}`);

输出结果为:
在这里插入图片描述

  1. 查找一段字符串中出现的最多字母和次数。
let str = "    dffiu  aefiueuf";
let num = str.match(/[a-zA-Z]/g).length;
let len = str.match(/[a-zA-Z]/g);
let obj = {};
for (let i = 0; i < len.length; i++) {
  let key = len[i];
  if (!obj[key]) {
    obj[key] = [1];
  } else {
    obj[key].push(1);
  }  
}

let max = 0, name;
let all = [];
for (let key in obj) {
  if (obj[key].length === max) {
    max = obj[key].length;
    all.push(key);
  } else if (obj[key].length > max) {
    max = obj[key].length;
    all = [];
    all[0] = key;
  }
}
console.log(`最大的为${all}出现了${obj[all[0]].length}次`);

输出结果为;
javascript查找并输出英语文章出现最多次数单词,和英语字符中出现最多字母_第1张图片

你可能感兴趣的:(javascript查找并输出英语文章出现最多次数单词,和英语字符中出现最多字母)