JS实现文本域匹配关键词数组计数后动态切换页面背景色
问题说明
原有代码的核心缺陷有两点:
- 仅用
includes()判断词汇是否存在,无法统计同一词汇多次出现的场景 - 遍历词汇时直接设置背景色,后续遍历到的反向词汇会直接覆盖之前的颜色设置,完全没有做总次数对比的逻辑
修正逻辑
- 分别设置
goodCount、badCount两个变量作为正向、负向词的总次数计数器,初始值为0 - 遍历词表时,通过全局正则匹配统计单个词汇在输入内容中的实际出现次数,累加到对应计数器
- 所有词汇统计完成后,再对比两个计数器的总数值,设置对应背景色:正向词次数更高用
goodColor,负向词次数更高用badColor,次数相等可重置为默认背景色
可直接运行的修正代码
const goodWords = ['happy', 'joyful', 'amazing', 'enjoyed', 'fun', 'excited', 'nice', 'funny', 'fantastic', 'good', 'calm', 'comfortable', 'glad', 'confident', 'kind']; const badWords = ['angry', 'sad', 'upset', 'defeated', 'embarrassed', 'jealous', 'nervous', 'anxious', 'unhappy', 'miserable', 'worst', 'bad']; const goodColor = 'rgb(225,225,56,0.2)' // 修正了原rgba值的alpha参数写法,原写法透明度参数超出0-1取值范围属于无效值 const badColor = 'rgb(100,100,50,0.5)' const textArea = document.querySelector('textarea'); // 补充原代码缺失的textarea元素获取逻辑,可根据实际页面选择器修改 textArea.addEventListener('input', function () { let goodCount = 0; let badCount = 0; const inputContent = textArea.value.toLowerCase(); // 统一转小写,实现大小写不敏感匹配 // 统计正向词总出现次数 for (const word of goodWords) { // 加\b词边界匹配独立单词,避免匹配到长单词中包含的短词(比如避免good误匹配到goodness中的字符片段) const matchReg = new RegExp(`\\b${word}\\b`, 'g'); const matchResult = inputContent.match(matchReg); goodCount += matchResult ? matchResult.length : 0; } // 统计负向词总出现次数 for (const word of badWords) { const matchReg = new RegExp(`\\b${word}\\b`, 'g'); const matchResult = inputContent.match(matchReg); badCount += matchResult ? matchResult.length : 0; } // 对比总次数设置背景色 if (goodCount > badCount) { document.body.style.backgroundColor = goodColor; } else if (badCount > goodCount) { document.body.style.backgroundColor = badColor; } else { // 次数相等时重置为默认背景,可根据需求自行修改 document.body.style.backgroundColor = ''; } })
注:如果不需要做独立单词匹配,只想统计字符串中出现的字符片段(比如要让
good命中goodbye中的片段),把正则里的\\b词边界标识去掉即可。
内容的提问来源于stack exchange,提问作者rafflewinner64
相关产品推荐
相关产品推荐

