An excellent place to begin would be https://gist.github.com/evenfrost/1ba123656ded32fb7a0cd4651efd4db0
const highlightText = (searchResults: any, className: string = 'highlight') => {
const setProperty = (obj: object, path: string, value: any) => {
const pathArr = path.split('.');
let index;
for (index = 0; index < pathArr.length - 1; index++) {
obj = obj[pathArr[index]];
}
obj[pathArr[index]] = value;
};
const createHighlightedContent = (input: string, regions: number[] = []) => {
let content = '';
let nextUnhighlightedRegionStartIndex = 0;
regions.forEach(region => {
const lastRegionNextIndex = region[1] + 1;
content += [
input.substring(nextUnhighlightedRegionStartIndex, region[0]),
`<span class="${className}">`,
input.substring(region[0], lastRegionNextIndex),
'</span>',
].join('');
nextUnhighlightedRegionStartIndex = lastRegionNextIndex;
});
content += input.substring(nextUnhighlightedRegionStartIndex);
return content;
};
return searchResults
.filter(({ matches }: any) => matches && matches.length)
.map(({ item, matches }: any) => {
const highlightedItem = { ...item };
matches.forEach((match: any) => {
setProperty(highlightedItem, match.key, createHighlightedContent(match.value, match.indices));
});
return highlightedItem;
});
};
// example of usage:
const result = highlightText(fuse.search(text)); // array of items with highlighted fields