regex 如何在react中搜索多个单词时突出显示段落中所有匹配的单词

wqlqzqxt  于 2022-12-24  发布在  React
关注(0)|答案(1)|浏览(120)

我有一个显示搜索结果的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'。

mspsb9vt

mspsb9vt1#

我是新来的,但也许这会有所帮助:(hello)|(world).
regex101.com

相关问题