0

我在 Next JS/Typescript Web 应用程序中使用了 Fuse.js 库。我不确定该includeMatches选项如何用于突出显示目的。如果我使用该选项,我会matches在结果对象中得到一个对象,其中包含一大堆 from 和 to 索引,它似乎比实际匹配的要多。

我怎样才能使用这个数组来突出显示?任何人?

4

1 回答 1

0

一个好的起点是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
于 2021-09-15T08:07:16.910 回答