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

React.js多关键词文本高亮失效问题求助

修复React多关键词文本高亮问题

问题原因

你的代码仅针对第一个关键词"Aloe Vera"创建正则并执行文本分割逻辑,第二个关键词"skin"只是被简单追加到matches数组,并未参与文本分割与匹配流程,因此无法实现高亮。

修复方案

将所有关键词合并为一个正则表达式,保留每个关键词的原始匹配格式(含大小写),通过分割文本与匹配结果的对应关联,实现多关键词高亮。

修改后的完整代码:

import React from "react";

function App() {
  const highlightMatchingText = (text, ...keywords) => {
    // 转义关键词中的正则特殊字符,避免语法冲突
    const escapedKeywords = keywords.map(keyword => 
      keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    );
    // 合并关键词为正则,开启全局匹配与忽略大小写模式
    const matchRegex = new RegExp(escapedKeywords.join("|"), "ig");
    
    // 获取所有匹配结果,保留原始大小写
    const matches = [...text.matchAll(matchRegex)].map(match => match[0]);
    // 用正则分割文本
    const splitText = text.split(matchRegex);
    
    return splitText.map((nonHighlighted, index) => (
      <React.Fragment key={index}>
        {nonHighlighted}
        {/* 存在匹配项时才渲染高亮标签 */}
        {matches[index] && <mark>{matches[index]}</mark>}
      </React.Fragment>
    ));
  };
  
  return (
    <p>
      {highlightMatchingText(
        "The aim of this study was to determine in vitro the potential of Aloe Vera juice as a skin permeation enhancer; a secondary aim was to probe the extent to which Aloe Vera itself permeates the skin. Saturated solutions of caffeine, colchicine, mefenamic acid, oxybutynin, and quinine were prepared at 32 degrees C in Aloe Vera juice and water (control) and used to dose porcine ear skin",
        "Aloe Vera",
        "skin"
      )}
    </p>
  );
}

export default App;

关键修改说明

  • 采用剩余参数...keywords:让函数支持传入任意数量的关键词,提升扩展性。
  • 转义正则特殊字符:避免关键词中的., *等特殊字符破坏正则语法。
  • 合并关键词正则:用|分隔多个关键词,实现同时匹配任意目标关键词。
  • 关联分割文本与匹配结果:利用splitText与matches的长度对应关系,通过matches[index]判断是否存在后续匹配项,避免渲染空高亮标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:15:49