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

What changes can I make to my React components to prevent them from constantly re-rendering?

In my Next.js project, I have a page that displays the content of a transcript and allows users to select portions of the text and make notes on it. The issue I'm facing is outlined below Inside the getServersideProps function, I retrieve a link to ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

What is the best way to ensure all keys of a certain type are mandatory, while still allowing for the possibility of

I am looking to create a mapping of key/value pairs for a specific type in the following way: required_key: string | undefined transformed to required_key: string | undefined (remains the same) required_key: string transformed to required_key: string (rem ...

Having trouble with NextJS not updating state upon button click?

I am encountering a problem with my NextJS application. I am attempting to show a loading spinner on a button when it is used for user login. I have tried setting the `loading` state to true before calling the login function and then reverting it to fals ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Identifying Flaws in Components during Creation with Ready-Made spec.ts Files

Currently, I have embarked on the journey of creating unit tests for my Angular Material project. At the moment, my focus is on testing whether the pre-made spec.ts files for each component are passing successfully. Despite the fact that my project compile ...

Exploring methods for monitoring page transitions in Next.js

Looking to repurpose a menu I created in react using react-router-dom for use in nextjs. My objective is to update the menu state to 'false' and change the menuName to 'menu' upon clicking on a link within the menu. Implemented a useEf ...

Navigating json data in angular 6

I retrieved a JSON object in the following format response = [ { 'a': [ { 'b': [ { 'c': [ { 'name': 'abc', 'value': 900 ...

Utilizing interface in NestJS for validating incoming request parameters

My goal is to utilize the interface provided by class-validator in order to validate a specific field in the incoming request body. Here's the interface structure: export enum Fields { Full_Stack_Dev = 'full stack dev', Frontend_Dev = &a ...

Water supply running low in the nextJS Vercel project

An error message is displayed below. After rendering your application in NextJS, there appears to be a discrepancy between the pre-rendered React tree (SSR/SSG) and the one rendered during the initial browser render. This process, known as Hydration, is a ...

An issue has been detected with retrieving data on mobile devices using SWR in Next.js, resulting in an error during

I am currently working on implementing client-side data fetching using swr within my application built with nextjs. The data fetched using the useSWR hook is displaying correctly in my desktop browser. However, when I try to access the app from my mobile b ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

Exiting NextJs - Close Window or Tab

When working with Next.js / React.js, finding out whether the user clicks the close tab or close window button can be a bit tricky. I have searched for references but haven't found a solution yet. Maybe there are other sources that can help. My goal ...

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Receiving an error when attempting to inject the Router in a component constructor without using the elvis operator

Upon launching my app, I desire the route /home to be automatically displayed. Unfortunately, the Angular 2 version I am utilizing does not support the "useAsDefault: true" property in route definitions. To address this issue, I considered implementing th ...

What is the reason behind continuously receiving the error message stating "Not all code paths return a value here"?

Can someone help me understand why I am consistently encountering this error message from typescript? PS. I am aware that in this scenario I could simply use a boolean and not create a function, but my focus here is on typescript. I keep receiving the er ...

Issue with deploying production build in Next.js causing 404 errors on sub pages

After deploying my Next.js build code to production using the command next export -o outDir, I noticed that only the home page is working. When attempting to access /login, I am receiving a 404 error. Can anyone offer guidance on how to resolve this issu ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Issue: The module '@nx/nx-linux-x64-gnu' is not found and cannot be located

I'm encountering issues when trying to run the build of my Angular project with NX in GitHub Actions CI. The process fails and displays errors like: npm ERR! code 1 npm ERR! path /runner/_work/myapp/node_modules/nx npm ERR! command failed npm ERR! c ...