Autosuggest Highlight
Utilities for highlighting text in autosuggest and autocomplete components.
Installation
yarn add autosuggest-highlight
or
npm install autosuggest-highlight --save
API
Function | Description |
---|---|
match(text, query, options) |
Calculates the characters to highlight in text based on query . |
parse(text, matches) |
Breaks the given text to parts based on matches . |
match(text, query, options)
Calculates the characters to highlight in text
based on query
.
It returns an array of pairs. Every pair [a, b]
means that text.slice(a, b)
should be highlighted.
Options are passed as JSON.
Option | Description |
---|---|
insideWords | boolean false by default. Searches inside words |
findAllOccurrences | boolean false by default. Finds all occurrences of each match |
requireMatchAll | boolean false by default. Requires each word of query to be found in text or else returns an empty set |
Examples
We match at the beginning of a word by default:
var match = ; // text indices: 012345678// highlighting: vvvar matches = ; // [[5, 7]]
// text indices: 012345678// highlighting:var matches = ; // []
Enable search inside words:
var match = ; // text indices: 012345678// highlighting: vvar matches = ; // [[2, 3]]
When query
is a single word, only the first match is returned by default:
// text indices: 012345678901234// highlighting: vvar matches = ; // [[0, 1]]
You'll get the second match, if query
contains multiple words:
// text indices: 012345678901234// highlighting: v vvar matches = ; // [[0, 1], [5, 6]]
Or using the findAllOccurrences option:
// text indices: 012345678901234// highlighting: v vvar matches = ; // [[0, 1], [5, 6]]
Matches are case insensitive:
// text indices: 012345678// highlighting: vvar matches = ; // [[5, 6]]
and diacritics are removed:
// text indices: 0123456// highlighting: vvvvvar matches = ; // [[0, 4]]
When query
has multiple words, the order doesn't matter:
// text indices: 012345678901234// highlighting: v vvar matches = ; // [[0, 1], [7, 8]]
// text indices: 012345678901234// highlighting: v vvar matches = ; // [[0, 1], [7, 8]]
parse(text, matches)
Breaks the given text
to parts based on matches
.
It returns an array of text
parts by specifying whether each part should be highlighted or not.
For example:
var parse = ; // text indices: 0123456789012345// highlighting: vv vvar parts = ;/* [ { text: 'Pretty ', highlight: false }, { text: 'co', highlight: true }, { text: 'ol ', highlight: false }, { text: 't', highlight: true }, { text: 'ext', highlight: false } ]*/