Skip to content

Commit b39c595

Browse files
committed
Fix table cell renderer highlighting of search term matches
Use global regex to get all matching strings not only the first match. Handle different behavior of String.split() when regex contains capturing groups. Fixes #1160 Signed-off-by: Patrick Tasse <patrick.tasse@gmail.com>
1 parent efe4066 commit b39c595

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

packages/react-components/src/components/table-renderer-components.tsx

+23-9
Original file line numberDiff line numberDiff line change
@@ -50,24 +50,38 @@ export class CellRenderer extends React.Component<CellRendererProps> {
5050
const searchTerm = (currField && this.props.filterModel.get(currField)) || '';
5151
if (this.props.filterModel.size > 0) {
5252
if (isMatched) {
53+
const regex = new RegExp(searchTerm, 'g');
54+
const matches = currFieldVal.match(regex);
5355
cellElement = (
5456
<>
55-
{currFieldVal
56-
.split(new RegExp(searchTerm))
57-
.map((tag: string, index: number, array: string[]) => (
58-
<span key={index.toString()}>
59-
<>{tag}</>
57+
{currFieldVal.split(regex).map((tag: string, index: number, array: string[]) => (
58+
<span key={index.toString()}>
59+
{array.length > matches.length + 1 ? (
60+
// regex contains groups, evens are non-matching strings, odds are captured groups or undefined
6061
<>
61-
{index < array.length - 1 ? (
62+
{index % 2 === 0 ? (
63+
<>{tag}</>
64+
) : (
65+
<span style={{ backgroundColor: this.props.searchResultsColor }}>
66+
{matches[(index / 2) | 0]}
67+
</span>
68+
)}
69+
</>
70+
) : (
71+
// regex does not contain groups, all elements are non-matching strings
72+
<>
73+
{tag}
74+
{index < matches.length ? (
6275
<span style={{ backgroundColor: this.props.searchResultsColor }}>
63-
{currFieldVal.match(new RegExp(searchTerm))[0]}
76+
{matches[index]}
6477
</span>
6578
) : (
6679
<></>
6780
)}
6881
</>
69-
</span>
70-
))}
82+
)}
83+
</span>
84+
))}
7185
</>
7286
);
7387
} else {

0 commit comments

Comments
 (0)