Autosuggest Highlight
Utilities for highlighting text in autosuggest and autocomplete components.
Installation
yarn add autosuggest-highlight
or
npm install autosuggest-highlight --save
API
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 = require('autosuggest-highlight/match');
var matches = match('some text', 'te');
var matches = match('some text', 'e');
Enable search inside words:
var match = require('autosuggest-highlight/match');
var matches = match('some text', 'm', { insideWords: true });
When query
is a single word, only the first match is returned by default:
var matches = match('some sweet text', 's');
You'll get the second match, if query
contains multiple words:
var matches = match('some sweet text', 's s');
Or using the findAllOccurrences option:
var matches = match('some sweet text', 's', { findAllOccurrences: true });
Matches are case insensitive:
var matches = match('Some Text', 't');
and diacritics are removed:
var matches = match('Déjà vu', 'deja');
When query
has multiple words, the order doesn't matter:
var matches = match('Albert Einstein', 'a e');
var matches = match('Albert Einstein', 'e a');
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 = require('autosuggest-highlight/parse');
var parts = parse('Pretty cool text', [[7, 9], [12, 13]]);
Usage with old browsers
For using this library with old browsers such as IE11 you must change import to
var match = require('autosuggest-highlight/ie11/match');
var parse = require('autosuggest-highlight/ie11/parse');
License
MIT