简体   繁体   English

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

[英]How to highlight all matching words in a paragraph when searching multiple words in react

I have a JSX element that displays a search result and the result has the matching search term highlighted wherever it appears in the result.我有一个显示搜索结果的 JSX 元素,并且该结果在结果中出现的任何位置都突出显示了匹配的搜索词。 For instance if searchTerm = 'hello world' and result.text = 'foo bar hello world it is hello' , it will be highlighted like so: 'foo bar hello world it is hello'.例如,如果searchTerm = 'hello world'result.text = 'foo bar hello world it is hello' ,它将像这样突出显示:'foo bar hello world it is hello'。 This solution only works for perfect matches however.但是,此解决方案仅适用于完美匹配。

// 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>
    );
}

How could I modify the regex to have any matching word be highlighted in the text?我如何修改正则表达式以在文本中突出显示任何匹配的词? So the searchTerm would have to be split up into individual words and the resulting highlights would be 'foo bar hello world it is hello '.所以 searchTerm 必须被拆分成单独的单词,结果突出显示是“foo bar hello world it is hello ”。

I am new to react, but maybe this will help: (hello)|(world) .我是新手,但也许这会有所帮助: (hello)|(world)

regex101.com正则表达式101.com

Here is a modified highlightMatch() function using plan JavaScript so that it can be shown here in the JS snippet -- you can convert that back into TypeScript:这是一个使用计划 JavaScript 修改的highlightMatch()函数,因此它可以在 JS 片段中显示在这里——您可以将其转换回 TypeScript:

 function highlightMatch(searchTerm, text) { const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp('\\b' + escapedTerm + '\\b', 'gi'); return text.replace(regex, m => '<span class="highlightText">' + m + '</span>'); } const text = 'foo bar hello world it is hello'; const searchTerm = 'hello world'; let result = highlightMatch(searchTerm, text); console.log(result); document.getElementById('result').innerHTML = result;
 .highlightText { font-weight: bold; background-color: yellow; }
 <div id="result"></div>

Notes:笔记:

  • the search term needs to be escaped, so that chars special to regex can be searched literally: /[.*+?^${}()|[\]\\]/g需要转义搜索词,以便可以按字面搜索正则表达式的特殊字符:/[.*+?^${}( /[.*+?^${}()|[\]\\]/g /g
  • the search regex is created dynamically with the escaped search term搜索正则表达式是使用转义的搜索词动态创建的
  • the search term uses \b word boundaries to avoid false hits, such as text highlighted with text light (remove the word boundaries if you want to highlight text within words)搜索词使用\b字边界来避免错误命中,例如用文本light highlighted的文本(如果要突出显示字内的文本,请删除字边界)
  • the .replace() encloses the matched text in a span with class highlightText .replace()将匹配的文本包含在具有highlightText类的范围内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 react-highlight-words 突出显示具有不同 colors 的多个关键字 - how to use react-highlight-words to highlight multiple keywords with different colors 如何通过单击按钮在 JavaScript 中突出显示多个单词 - How to highlight multiple words in JavaScript with button click 如何使用正则表达式突出显示字符串中的多个关键字/词? - How to highlight multiple keywords/words in a string with Regex? 如何使用“突出显示文本区域”插件突出显示多个单词 - How to highlight multiple words with the Highlight Text Area plugin 突出显示Chrome扩展程序中的所有单词 - Highlight All Words in Chrome Extension JavaScript和CSS:突出显示具有相同背景的多个单词 - JavaScript and css: highlight multiple words all with same background 如何在Javascript中使用正则表达式检查多个匹配的单词 - How to check multiple matching words with regex in Javascript 如何从React Native中的段落中检测样式,特定单词的超链接 - How to detect styles, hyperlinks for particular words from a paragraph in React Native 打字稿或Javascript:搜索多个单词 - Typescript or Javascript: searching for multiple words 忽略HTML标记以突出显示匹配的单词 - Ignoring HTML tags to highlight matching words
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM