Skip to main content
The highlighting system provides character-level ranges for matched tokens without generating HTML. This keeps the library UI-agnostic while giving you complete control over rendering.

Overview

The getHighlightRanges() 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 (typically verse.uthmani)
  • matchedTokens: readonly string[] | undefined - Tokens matched by the search
  • tokenTypes?: Record<string, MatchType> - Optional map of token to match type
Returns: HighlightRange[]

HighlightRange type

From src/utils/highlight.ts:4-9:
Fields:
  • start - Starting character index (inclusive)
  • end - Ending character index (exclusive)
  • token - The original query token that matched
  • matchType - 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.

Character variant handling

The regex generator handles Arabic character variants to ensure robust matching:
The regex patterns allow optional diacritics between every character, so “الله” will match “ٱللَّهِ” even with full tashkeel.

Empty results

If no tokens are provided or no matches are found, the function returns an empty array:
Always check if ranges are empty before attempting to render highlights. Rendering logic should gracefully handle empty range arrays.

Other frameworks

While the React example is shown above, the same principle applies to any framework:

Vue example

Vanilla JavaScript example