Overview
ThegetHighlightRanges() function computes non-overlapping highlight ranges from search results. The consumer controls rendering - no dangerouslySetInnerHTML required.
Basic usage
getHighlightRanges(text, matchedTokens, tokenTypes?)
Parameters:
text: string- The text to highlight (typicallyverse.uthmani)matchedTokens: readonly string[] | undefined- Tokens matched by the searchtokenTypes?: Record<string, MatchType>- Optional map of token to match type
HighlightRange[]
HighlightRange type
Fromsrc/utils/highlight.ts:4-9:
start- Starting character index (inclusive)end- Ending character index (exclusive)token- The original query token that matchedmatchType- Type of match:'exact' | 'lemma' | 'root' | 'fuzzy' | 'none'
Ranges are non-overlapping and sorted by position. If tokens overlap, the longest match takes priority.
React rendering example
From the README, here’s how to render highlights in React:Styling by match type
How it works
1
Diacritic-aware regex creation
For each matched token, create a regex pattern that matches the token with optional diacritics and handles character variants.From
src/utils/highlight.ts:17-36:2
Find all matches
For each token, find all matching positions in the text and record their ranges with priority based on match length.
3
Sort by priority
Sort matches by length (longer matches first), then by position.
4
Remove overlaps
Keep only non-overlapping ranges using a character occupation tracker.
5
Sort by position and return
Sort final ranges by starting position and remove internal priority field.