import React from "react";
function App() {
const highlightMatchingText = (text, matchingText, secondMatch) => {
const matchRegex = RegExp(matchingText, "ig");
// Matches array needed to maintain the correct letter casing
const matches = [...text.matchAll(matchRegex)];
matches.push([secondMatch]);
console.log(matches);
return text.split(matchRegex).map((nonBoldText, index, arr) => (
<React.Fragment key={index}>
{nonBoldText}
{index + 1 !== arr.length && <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;
如果我通过多个不同的关键字作为args我需要突出显示在文本中,但它只在一个关键字(一个参数)请帮助我如何解决它,“芦荟”,是工作,但“皮肤”不工作
”
https://codesandbox.io/s/jolly-benz-gqf11i?file=/src/App.js:0-1142
2条答案
按热度按时间wpx232ag1#
我将
matchingText
改为一个数组,您可以在其中放置所有想要匹配的文本。然后在RegExp
中,我们将textToMatch
与|
连接。这将匹配“Aloe Vera”或“skin”。在此处检查live version
希望这对你的项目有帮助!
7nbnzgx92#
试试这个:https://www.npmjs.com/package/react-multi-highlightreact组件根据每个配置突出显示文本中的多个单词