You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ReactJS高亮显示textarea输入文本中出现频率最高的字符

React 实现文本高频字符高亮的完整方案

核心调整逻辑:

  • 基于已有的字符统计结果,按出现次数倒序排序取前5位最高频字符
  • 新增高亮字符渲染逻辑,保留原始文本的空格、换行格式的前提下标记高频字符
  • 新增前5高频字符总出现次数的统计展示
import React, { useState, useMemo } from "react";

// 高亮样式可根据需求自行调整
const highlightStyle = {
  backgroundColor: "#ffeb3b",
  fontWeight: "bold"
};

// 去除空格用于字符统计
const removeSpace = (text) => text.replace(/\s/g, "");

function Home() {
  const [text, setText] = useState("");

  // 原有字符统计逻辑
  const eachCharResult = useMemo(() => {
    let result = {};
    let textWithoutSpace = removeSpace(text);
    for (let i = 0; i < textWithoutSpace.length; i++) {
      const char = textWithoutSpace[i];
      result[char] = result[char] ? result[char] + 1 : 1;
    }
    return result;
  }, [text]);

  // 新增:计算前5高频字符、总出现次数
  const { top5Chars, top5TotalCount } = useMemo(() => {
    const sortedChars = Object.entries(eachCharResult)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5); // 取前5位,可自行修改数量
    return {
      top5Chars: sortedChars.map(item => item[0]),
      top5TotalCount: sortedChars.reduce((sum, item) => sum + item[1], 0)
    };
  }, [eachCharResult]);

  // 新增:渲染带高亮的原始文本
  const renderedText = useMemo(() => {
    if (!text) return null;
    return text.split("").map((char, index) => {
      // 空格换行不需要高亮直接返回
      if (/\s/.test(char)) return char;
      // 匹配到高频字符则包裹高亮标签
      if (top5Chars.includes(char)) {
        return <span key={index} style={highlightStyle}>{char}</span>;
      }
      return char;
    });
  }, [text, top5Chars]);

  return (
    <div style={{ padding: "20px", maxWidth: "800px", margin: "0 auto" }}>
      <form>
        <h3>请输入文本</h3>
        <textarea
          onChange={(e) => setText(e.target.value)}
          placeholder="开始输入"
          style={{ width: "100%", height: "150px", padding: "10px", marginBottom: "10px" }}
        ></textarea>
        <p>总字符数(不含空格):{removeSpace(text).length}</p>
        <p>前5高频字符总出现次数:{top5TotalCount}</p>
      </form>

      {/* 高亮文本展示区域 */}
      <div style={{ margin: "20px 0", padding: "15px", border: "1px solid #eee", whiteSpace: "pre-wrap" }}>
        <h4>高亮后文本:</h4>
        {renderedText}
      </div>

      {/* 字符频率统计列表,前5位标注最高频 */}
      <div>
        <h4>字符出现频率:</h4>
        {Object.entries(eachCharResult)
          .sort((a, b) => b[1] - a[1])
          .map(([char, count], i) => (
            <p key={i}>
              {`${char}: ${count}`}
              {i < 5 && <span style={{ marginLeft: "10px", color: "#f44336" }}>(最高频字符)</span>}
            </p>
          ))}
      </div>
    </div>
  );
}
export default Home;

可选调整说明:

  • 如果需要不区分大小写统计,在统计字符时把字符统一转成小写/大写即可
  • 高亮样式、取高频字符的数量都可以根据需求自行修改
  • 不需要保留原始换行的话可以去掉高亮容器的whiteSpace: "pre-wrap"属性

内容的提问来源于stack exchange,提问作者Notation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:06:03