Getting started
Install
npm i lucid-searchOr load the UMD build from a CDN. It exposes the global lucidSearch:
<script src="https://unpkg.com/lucid-search/build/lucid-search.js"></script>Find matches
import { findRanges, toSegments } from 'lucid-search';
const haystack = 'The quick brown fox jumps over the lazy dog';
const ranges = findRanges(haystack, 'The dog');
// [{ start: 0, end: 3 }, { start: 31, end: 34 }, { start: 40, end: 43 }]
toSegments(haystack, ranges);
// [
// { text: 'The', match: true },
// { text: ' quick brown fox jumps over ', match: false },
// { text: 'the', match: true },
// { text: ' lazy ', match: false },
// { text: 'dog', match: true }
// ]The query is split on whitespace, so each term is searched on its own. Matching ignores case and accents, and terms are plain text: c++ or ( match themselves.
Forgive typos
findRanges('Pride and Prejudice', 'prejudcie', { typos: 1 });
// [{ start: 10, end: 19 }]typos is the most typos a term may have: an inserted, deleted or replaced letter, or two adjacent letters swapped. A term gets at most one typo per 4 letters, because short terms with typos match almost anything. Each Range covers the best match: whole words, without the space or letters around them. score ranks a match with typos like an exact one of the same length. See the benchmarks against Fuse.js, uFuzzy and fuzzysort.
Match only at word starts
findRanges('Feliz and Lina', 'li', { wordStart: true });
// [{ start: 10, end: 12 }]If your server matches terms by prefix only, for example with a Postgres regex (^|[^[:alnum:]])term or a tsquery prefix term:*, set wordStart so the highlight agrees: li then marks Lina but not Feliz. See Highlighting Postgres results.
Render in React
import { findRanges, toSegments } from 'lucid-search';
function Highlight({ text, query }: { text: string; query: string }) {
return toSegments(text, findRanges(text, query)).map((segment, i) =>
segment.match ? <mark key={i}>{segment.text}</mark> : segment.text
);
}No HTML string is ever built, so a haystack like <img onerror=…> stays plain text.
For an excerpt in a result list, cut the segments to a window of 160 characters around the first match with toSnippet, and render them the same way. Where text was cut, it adds a … segment that is not a match.
import { findRanges, toSegments, toSnippet } from 'lucid-search';
function Excerpt({ text, query }: { text: string; query: string }) {
return toSnippet(toSegments(text, findRanges(text, query)), 160).map((segment, i) =>
segment.match ? <mark key={i}>{segment.text}</mark> : segment.text
);
}