React高亮显示整个单词的搜索结果,并使用正则表达式区分大小写进行搜索



我正在制作一个React突出显示组件,以突出显示结果段落中的关键字
该组件接受一组关键字和文本(搜索结果(。

我的目标是数组中的任何关键字,如果在文本中找到,都应该用不同的颜色突出显示。

export default function HighlightWord(props) {
const { keyWords, text } = props;
const highLightWords = keyWords.filter((keyword) => {
return keyword !== "";
});
//just color use on highlight, so far just assume only four keywords in the array
const color = [
"#f3ff33",
"#e285f5",
"#c8fae9",
"#f5e385",
];
let tempArray = [];
let keyValue = 0;
// so each keyword with has its color
for (let i = 0; i < highLightWords.length; i++) {
tempArray[i] = [highLightWords[i], color[i]];
}
return text && highLightWords.length ? (
<div>
{textToHighlight
.split(
new RegExp(
`(?<=${highLightWords.join("|")})|(?=${highLightWords.join("|")})`
)
)
.map((str) => {
if (highLightWords.includes(str)) {
let colorIndex = 0;
for (let i = 0; i < tempArray.length; i++) {
if (tempArray[i][0] == str) {
colorIndex = i;
}
}
return (
<span
key={`${str}` + `${keyValue++}`}
style={{ backgroundColor: color[colorIndex] }}
>
{str}
{console.log(str)}
</span>
);
} else {
return str;
}
})}
</div>
) : (
<>{text || ""}</>
);
}

我有两个问题不知道怎么解决。

第一个是,由于某些原因,关键字都是小写的,但文本是正常格式的,所以如果我使用text.includs(keywords[index](,在某些情况下它不会在文本中找到关键字。如何修改正则表达式使其不区分大小写。

第二个问题是,如果在关键字数组中,一个元素是另一个元素子串,例如,["流感"、"流感","健康"、"药物"],则函数只会突出显示"流感";流感"健康;以及";药物";。它还将突出";流感;流感内部,但流感本身不会被强调。如何在正则表达式上修复此问题?谢谢

  1. 使用text.toLowerCase((.includes(keywords[index](
  2. 按单词拆分文本-text.split(''(并使用length-keywords按降序对关键字进行排序。sort((i,j(=>j.length-i.length(。然后检查文本中每个拆分单词的关键字位置

let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
let highLightWords = ["lorem", "olo", "dolor"];
highLightWords.sort((i, j) => j.length - i.length);
text.toLowerCase()
.split(' ')
.map((str, index) => {
for (let i = 0; i < highLightWords.length; i++) {
let temp = str.search(highLightWords[i]);
if (temp >= 0) {
console.log(str.substring(temp, temp + highLightWords[i].length));
//break;
}
}
});

最新更新