UI Libraries / Autocomplete / parseAlgoliaHitReverseSnippet

parseAlgoliaHitReverseSnippet

The parseAlgoliaHitReverseSnippet function lets you parse the non-highlighted parts of an Algolia hit’s snippet. 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.

1
2
3
yarn add @algolia/autocomplete-preset-algolia
# or
npm install @algolia/autocomplete-preset-algolia

Then import it in your project:

1
import { parseAlgoliaHitReverseSnippet } from '@algolia/autocomplete-preset-algolia';

If you don’t use a package manager, you can use the HTML script element:

1
2
3
4
5
6
<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-preset-algolia"></script>
<script>
  const { parseAlgoliaHitReverseSnippet } = window[
    '@algolia/autocomplete-preset-algolia'
  ];
</script>

Examples

With a single string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { parseAlgoliaHitReverseSnippet } from '@algolia/autocomplete-preset-algolia';

// An Algolia hit for query "zelda"
const hit = {
  query: 'zelda switch',
  _snippetResult: {
    query: {
      value: '__aa-highlight__zelda__/aa-highlight__ switch',
    },
  },
};
const reverseSnippetedParts = parseAlgoliaHitReverseSnippet({
  hit,
  attribute: 'query',
});

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

Example with nested attributes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { parseAlgoliaHitReverseSnippet } from '@algolia/autocomplete-preset-algolia';

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

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

Parameters

hit
type: AlgoliaHit
Required

The Algolia hit whose attribute to retrieve the reverse snippet from.

attribute
type: string | string[]
Required

The attribute to retrieve the reverse snippet from. You can use the array syntax to reference nested attributes.

Returns

type: ParsedAttribute[]

An array of the parsed attribute’s parts.

Did you find this page helpful?