Skip to main content
The parseAlgoliaHitReverseHighlight function lets you parse the non-highlighted parts of an Algolia hit. This is a common pattern for Query Suggestions, where you want to highlight the differences between each suggestion.
If you’re using autocomplete-js, all Algolia utilities are available directly in the package with the right user agents and the virtual DOM layer. You don’t need to import the preset separately.

Installation

First, you need to install the preset.
npm install @algolia/autocomplete-preset-algolia
Then import it in your project:
JavaScript
import { parseAlgoliaHitReverseHighlight } from "@algolia/autocomplete-preset-algolia";
If you don’t use a package manager, you can use the HTML script element:
HTML
<script
  src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-preset-algolia@1.19.4/dist/umd/index.production.js"
  integrity="hqqZsgytphUhmmnnfNd/A5wjXf0y4hifZNUTpRvy0wM="
  crossorigin="anonymous"
></script>
<script>
  const { parseAlgoliaHitReverseHighlight } = window["@algolia/autocomplete-preset-algolia"];
</script>

Examples

With a single string

JavaScript
import { parseAlgoliaHitReverseHighlight } from "@algolia/autocomplete-preset-algolia";

// An Algolia hit for query "zelda"
const hit = {
  query: "zelda switch",
  _highlightResult: {
    query: {
      value: "__aa-highlight__zelda__/aa-highlight__ switch",
    },
  },
};
const reverseHighlightedParts = parseAlgoliaHitReverseHighlight({
  hit,
  attribute: "query",
});

/*
 * [
 *  { value: 'zelda', isHighlighted: false },
 *  { value: ' switch', isHighlighted: true },
 * ]
 */

With nested attributes

JavaScript
import { parseAlgoliaHitReverseHighlight } from "@algolia/autocomplete-preset-algolia";

// An Algolia hit for query "video"
const hit = {
  hierarchicalCategories: {
    lvl1: "Video games",
  },
  _highlightResult: {
    hierarchicalCategories: {
      lvl1: {
        value: "__aa-highlight__Video__/aa-highlight__ games",
      },
    },
  },
};
const reverseHighlightedParts = parseAlgoliaHitReverseHighlight({
  hit,
  attribute: ["hierarchicalCategories", "lvl1"],
});

/*
 * [
 *  { value: 'Video', isHighlighted: false },
 *  { value: ' games', isHighlighted: true },
 * ]
 */

Parameters

hit
AlgoliaHit
The Algolia hit whose attribute to retrieve the reverse highlighted parts from.
attribute
string | string[]
The attribute to retrieve the reverse highlighted parts from. You can use the array syntax to reference nested attributes.

Returns

returns
ParsedAttribute[]
An array of the parsed attribute’s parts.
I