parseAlgoliaHitHighlight

Returns the highlighted parts of an Algolia hit.

The parseAlgoliaHitHighlight function lets you parse the highlighted parts of an Algolia hit.

note

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.

yarn add @algolia/autocomplete-preset-algolia@alpha
# or
npm install @algolia/autocomplete-preset-algolia@alpha

Then import it in your project:

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

If you don't use a package manager, you can use a standalone endpoint:

<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-preset-algolia@alpha"></script>

Examples#

With a single string#

import { parseAlgoliaHitHighlight } from '@algolia/autocomplete-preset-algolia';
// An Algolia hit for query "lap"
const hit = {
name: 'Laptop',
_highlightResult: {
name: {
value: '__aa_highlight__Lap__/aa_highlight__top',
},
},
};
const highlightedParts = parseAlgoliaHitHighlight({
hit,
attribute: 'name',
});
// [{ value: 'Lap', isHighlighted: true }, { value: 'top', isHighlighted: false }]

With nested attributes#

import { parseAlgoliaHitHighlight } from '@algolia/autocomplete-preset-algolia';
// An Algolia hit for query "lap"
const hit = {
name: {
type: 'Laptop',
},
_highlightResult: {
name: {
type: {
value: '__aa_highlight__Lap__/aa_highlight__top',
},
},
},
};
const highlightedParts = parseAlgoliaHitHighlight({
hit,
attribute: ['name', 'type'],
});
// [{ value: 'Lap', isHighlighted: true }, { value: 'top', isHighlighted: false }]

Parameters#

hit#

AlgoliaHit | required

The Algolia hit whose attribute to retrieve the highlighted parts from.

attribute#

string | string[] | required

The attribute to retrieve the highlighted parts from. You can use the array syntax to reference nested attributes.

Returns#

ParsedAttribute[]

An array of the parsed attribute's parts.