Skip to main content
The parseAlgoliaHitSnippet function lets you parse the highlighted parts of an Algolia hit’s snippet.
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 { parseAlgoliaHitSnippet } 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 { parseAlgoliaHitSnippet } = window["@algolia/autocomplete-preset-algolia"];
</script>

Examples

With a single string

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

// An Algolia hit for query "the"
const hit = {
  name: "The Legend of Zelda: Breath of the Wild",
  _snippetResult: {
    name: {
      value:
        "__aa-highlight__The__/aa-highlight__ Legend of Zelda: Breath of __aa-highlight__the__/aa-highlight__ Wild",
    },
  },
};
const snippetedParts = parseAlgoliaHitSnippet({
  hit,
  attribute: "name",
});

/*
 * [
 *  { value: 'The', isHighlighted: true },
 *  { value: ' Legend of Zelda: Breath of ', isHighlighted: false },
 *  { value: 'the', isHighlighted: true },
 *  { value: ' Wild', isHighlighted: false },
 * ]
 */

With nested attributes

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

// An Algolia hit for query "cam"
const hit = {
  hierarchicalCategories: {
    lvl1: "Cameras & Camcoders",
  },
  _snippetResult: {
    hierarchicalCategories: {
      lvl1: {
        value:
          "__aa-highlight__Cam__/aa-highlight__eras & __aa-highlight__Cam__/aa-highlight__coders",
      },
    },
  },
};
const snippetedParts = parseAlgoliaHitSnippet({
  hit,
  attribute: ["hierarchicalCategories", "lvl1"],
});

/*
 * [
 *  { value: 'Cam', isHighlighted: true },
 *  { value: 'eras & ', isHighlighted: false },
 *  { value: 'Cam', isHighlighted: true },
 *  { value: 'coders', isHighlighted: false },
 * ]
 */

Parameters

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

Returns

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