Skip to content

Instantly share code, notes, and snippets.

@roc-ld
Forked from evenfrost/highlight.ts
Created April 20, 2024 16:37
Show Gist options
  • Select an option

  • Save roc-ld/ec496b6d5c6790f03b508625fa44870b to your computer and use it in GitHub Desktop.

Select an option

Save roc-ld/ec496b6d5c6790f03b508625fa44870b to your computer and use it in GitHub Desktop.
Fuse.js with highlight
const highlight = (fuseSearchResult: any, highlightClassName: string = 'highlight') => {
const set = (obj: object, path: string, value: any) => {
const pathValue = path.split('.');
let i;
for (i = 0; i < pathValue.length - 1; i++) {
obj = obj[pathValue[i]];
}
obj[pathValue[i]] = value;
};
const generateHighlightedText = (inputText: string, regions: number[] = []) => {
let content = '';
let nextUnhighlightedRegionStartingIndex = 0;
regions.forEach(region => {
const lastRegionNextIndex = region[1] + 1;
content += [
inputText.substring(nextUnhighlightedRegionStartingIndex, region[0]),
`<span class="${highlightClassName}">`,
inputText.substring(region[0], lastRegionNextIndex),
'</span>',
].join('');
nextUnhighlightedRegionStartingIndex = lastRegionNextIndex;
});
content += inputText.substring(nextUnhighlightedRegionStartingIndex);
return content;
};
return fuseSearchResult
.filter(({ matches }: any) => matches && matches.length)
.map(({ item, matches }: any) => {
const highlightedItem = { ...item };
matches.forEach((match: any) => {
set(highlightedItem, match.key, generateHighlightedText(match.value, match.indices));
});
return highlightedItem;
});
};
// usage:
const res = highlight(fuse.search(text)); // array of items with highlighted fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment