Skip to content

highlight

highlight(item, positions, open, close, options?): string

Highlight matched characters in a search result string.

Use with SearchResult.positions from a search with includePositions: true. Positions count characters the way search results do: an ASCII item by character, any other item by grapheme cluster (an emoji with its modifiers or a letter with its combining marks is one position), so a marker never splits one. Grapheme clusters are found with Intl.Segmenter (by code point where it is unavailable). The result is a single string: the unmatched text, and the matched text wrapped in the markers (or passed through the callback), joined together.

highlight() does not escape anything by default. When building HTML from untrusted items, pass { escapeHtml: true }; to render with a UI framework such as React, build elements from highlightRanges instead.

Parameter Type
item string
positions readonly number[]
open string
close string
options? HighlightOptions

string

String markers

const results = search('fzy', ['fuzzy'], { includePositions: true });
highlight(results[0].item, results[0].positions, '<b>', '</b>');
// → '<b>f</b>uz<b>zy</b>'

Callback (custom markup, returned as a string)

highlight(result.item, result.positions, (matched) => `<mark>${matched}</mark>`);

Safe HTML from untrusted text

highlight('<b>&', [1], '<mark>', '</mark>', { escapeHtml: true });
// → '&lt;<mark>b</mark>&gt;&amp;'

highlight(item, positions, callback, options?): string

Highlight matched characters in a search result string.

Use with SearchResult.positions from a search with includePositions: true. Positions count characters the way search results do: an ASCII item by character, any other item by grapheme cluster (an emoji with its modifiers or a letter with its combining marks is one position), so a marker never splits one. Grapheme clusters are found with Intl.Segmenter (by code point where it is unavailable). The result is a single string: the unmatched text, and the matched text wrapped in the markers (or passed through the callback), joined together.

highlight() does not escape anything by default. When building HTML from untrusted items, pass { escapeHtml: true }; to render with a UI framework such as React, build elements from highlightRanges instead.

Parameter Type
item string
positions readonly number[]
callback (matched) => string
options? HighlightOptions

string

String markers

const results = search('fzy', ['fuzzy'], { includePositions: true });
highlight(results[0].item, results[0].positions, '<b>', '</b>');
// → '<b>f</b>uz<b>zy</b>'

Callback (custom markup, returned as a string)

highlight(result.item, result.positions, (matched) => `<mark>${matched}</mark>`);

Safe HTML from untrusted text

highlight('<b>&', [1], '<mark>', '</mark>', { escapeHtml: true });
// → '&lt;<mark>b</mark>&gt;&amp;'