我有一个显示搜索结果的JSX元素,匹配的搜索词在结果中出现的任何地方都将高亮显示,例如searchTerm = 'hello world'
和result.text = 'foo bar hello world it is hello'
,它将被高亮显示,如下所示:'foo barhello worldit is hello'。但是,此解决方案仅适用于完美匹配。
// JSX that displays a search result with matches highlighted
<div style={{ whiteSpace: 'normal' }}>
{highlightMatch(documentationIndexState.searchTerm, result.text)}
</div>
// highlight function
function highlightMatch(searchTerm: string, text: string) {
const parts = text.split(new RegExp(`(${searchTerm})`, 'gi'));
return (
<span>
{' '}
{parts.map((part, i) => (
<span
key={i}
style={
part.toLowerCase() === searchTerm.toLowerCase() ? { fontWeight: 'bold', color: 'yellow' } : {}
}
>
{part}
</span>
))}{' '}
</span>
);
}
如何修改正则表达式以突出显示文本中的任何匹配单词?因此,searchTerm必须被拆分为单个单词,而突出显示的结果将是'foo barhello worldit ishello'。
1条答案
按热度按时间mspsb9vt1#
我是新来的,但也许这会有所帮助:
(hello)|(world)
.regex101.com