实现效果:需要高亮的文字为’降水‘和’分钟’
实现:
/**
* 多关键字高亮显示
*/
import React from "react";
interface MultiKwHighLightProps {
text: string; //需要显示的文本
highLightWord: string[]; //需要高亮的字符串数组
className?: string; //高亮内容的className
}
export default function MultiKwHighLight(props: MultiKwHighLightProps) {
const { text, highLightWord, className, highLightStyle } = props;
const highLightWords = highLightWord.filter(keyword => {
return keyword !== "";
});
return text && highLightWord.length ? (
<div>
{text
.split(
new RegExp(
`(?<=${highLightWords.join("|")})|(?=${highLightWords.join("|")})`
)
)
.map(str => {
if (highLightWords.includes(str)) {
return (
<span
className={className ? className : undefined}
>
{str}
</span>
);
} else {
return str;
}
})}
</div>
) : (
<>{text || ""}</>
);
}
补充:当需要显示高亮字符中包含特殊字符时(正则中的特殊字符如 (、)、*、+、-等)或报错,导致页面空白
下面是关键字为12(时的报错
解决:将字符中的特殊字符转化为+特殊字符,即在特殊字符加上转义符,参考js正则在特殊字符前进行转义并加上原来的字符
/**
* 多关键字高亮显示
*/
import React from "react";
interface MultiKwHighLightProps {
text: string; //需要显示的文本
highLightWord: string[]; //需要高亮的字符串数组
className?: string; //高亮内容的className
highLightStyle?: React.CSSProperties; //高亮内容的style
}
export default function MultiKwHighLight(props: MultiKwHighLightProps) {
const { text, highLightWord, className, highLightStyle } = props;
const highLightWords = highLightWord.filter(keyword => {
return keyword !== "";
});
const highLightWordsCopy = highLightWords.map(keyword => {
// 字符中特殊符号的处理
if (
/(\+|\-|\&|\||\!|\(|\)|\{|\}|\[|\]|\^|\”|\~|\*|\?|\:|\\)/g.test(keyword)
) {
//把匹配到的特殊字符替换成转义符,再加上原来的字符
return keyword.replace(
/(\+|\-|\&|\||\!|\(|\)|\{|\}|\[|\]|\^|\”|\~|\*|\?|\:|\\)/g,
"\\" +
keyword.match(
/(\+|\-|\&|\||\!|\(|\)|\{|\}|\[|\]|\^|\”|\~|\*|\?|\:|\\)/g
)[0]
);
}
return keyword;
});
console.log(highLightWordsCopy);
return text && highLightWord.length ? (
<div>
{text
.split(
new RegExp(
`(?<=${highLightWordsCopy.join("|")})|(?=${highLightWordsCopy.join(
"|"
)})`
)
)
.map(str => {
if (highLightWords.includes(str)) {
return (
<span
className={className ? className : undefined}
style={
highLightStyle
? highLightStyle
: !className
? { color: "red" }
: {}
}
>
{str}
</span>
);
} else {
return str;
}
})}
</div>
) : (
<>{text || ""}</>
);
}