[英]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)
。
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:笔记:
/[.*+?^${}()|[\]\\]/g
/[.*+?^${}()|[\]\\]/g
/g\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
的文本(如果要突出显示字内的文本,请删除字边界).replace()
encloses the matched text in a span with class highlightText
.replace()
将匹配的文本包含在具有highlightText
类的范围内
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.