How does the highlighting feature in Fuse.js includeMatches function operate?

Currently, in my Next JS/Typescript web application, I am using the Fuse.js library. However, I am still uncertain about how the includeMatches option functions for highlighting purposes. Whenever I enable this option, I receive a matches object within the result object that includes numerous from and to indexes, which seems to be more than what is actually being matched.

If anyone has any insights on how to utilize this array for highlighting purposes, please share. Thank you!

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

Trouble with querying NG elements using "queryAll(By.css)" in Angular and Jasmin unit testing

I've encountered an unusual problem that needs to be resolved for me to successfully complete a unit test for a project I'm currently engaged in. Here is what my unit test currently looks like: it('should display the navbar list', ...

Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, ...

Encountered an issue while configuring the Apollo server - The type '() => void' cannot be assigned to type '() => DataSources<object>'

I need help with a TypeScript-related issue. I am struggling to implement the expected return type for the function dataSources in this scenario. Here is the code snippet: const dataSources = () => { quizzessApi: new QuizzessDataSource(); } const ...

Determine the data type of an individual attribute within a collection of classes

I am working with a series of classes that have a body property defined within them. Here is an example: class Foo { body: {foo: string} constructor(body: Record<string, string>) { this.body = { foo: body.foo } } } class Bar { body: {ba ...

Tips for maintaining tab state using Angular Material

In my Angular 8 application with Angular Material, I have implemented four tabs where each tab allows editing. However, when going back from the edit mode to the tabs, I want the last selected tab to remain selected. My approach so far is as follows: exp ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

The Next.js 13 internationalization website continues to redirect to the locale page despite my attempts to remove it

While working on my app with NextJs, I attempted to implement localisation, but it ended up causing confusion and issues. The application started lagging on the i18n route and became unresponsive, even after multiple attempts of restarting the development ...

What is the correct version compatibility matrix for Expo, NPM, Node, React Native, and TypeScript?

Currently, I am in the process of setting up React Native with TypeScript. Here are the steps I followed: npx react-native init MyApp --template react-native-template-typescript I made sure to install TypeScript as well: npm install -g typescript ' ...

What is the process for executing tests using cookies and authentication in GitHub Actions?

In my testing setup for a Next.js app using Cypress, I am utilizing Blitz.js which streamlines many configurations for me. One challenge I have encountered is that the authentication information stored in Cookies and Local Storage does not persist over htt ...

Typescript is failing to infer the definition of an object, even after conducting a thorough check

I am encountering an issue with the code structure below: interface Data { isAvailable: boolean; } const foo = (data: Data | undefined, error: boolean) => { const hasError = error || !data; if (!hasError) { if (data.isAvailable) // do so ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

Unable to install Typescript using npm

I recently started a tutorial on Typescript and wanted to install it globally using npm. npm i typescript -g However, I encountered an issue where the installation gets stuck on the first line and displays the following message: (⠂⠂⠂⠂⠂⠂⠂⠂ ...

What is causing the server not to function properly in Next.js 13.4?

I created a function where I declared the use of server with the following code, According to the documentation, cookies can only be modified in a Server Action or Route Handler. For more information, visit: https://nextjs.org/docs/app/api-reference/funct ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

Issue encountered when trying to bring in a component from a different module

I am attempting to import the 'OpenDialogContentComponent' component from Module A into Module B, however I am encountering this error: 'Cannot determine the module for class OpenDialogContentComponent in C:/Users/jitdagar/Desktop/TDP/pwt-u ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...