Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fuse.js includeMatches highlighting - How does it work?

I'm using the Fuse.js library in my Next JS/Typescript web application. I'm unsure of how the includeMatches option works for highlighting purposes. If I use that option, I get a matches object in the result object that contains a whole bunch of from and to indexes and it seems to be way more than is being actually matched.

How can I use this array for highlighting purposes? Anyone?

like image 817
Jon Th Avatar asked Dec 22 '25 15:12

Jon Th


1 Answers

A good starting point would be https://gist.github.com/evenfrost/1ba123656ded32fb7a0cd4651efd4db0

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
like image 92
Arka Roy Avatar answered Dec 24 '25 10:12

Arka Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!