Split text into highlighted segments for query term matches
Search results usually show the query terms highlighted inside each result. Building that markup as an HTML string is risky (it invites XSS) and couples the logic to one renderer. A cleaner design returns segments that any UI can render, for example by wrapping highlighted ones in <mark>.
Implement splitHighlights(text, query). It splits text into an ordered array of segments:
splitHighlights(text, query) // => Array<{ text: string, highlighted: boolean }>
query holds one or more terms separated by whitespace (spaces, tabs, or newlines). Leading, trailing, and repeated whitespace is ignored.toLowerCase() of both strings), and terms are matched literally: characters like ., $, or ( have no special meaning. Tests use only ASCII text.'ana' matches 'banana' at index 1 and at index 3).text gives back the original text with its original casing. No segment is empty, and two neighbouring segments never have the same highlighted value: overlapping or adjacent matches form one highlighted segment.text is empty, return [].splitHighlights('Grab a coffee and a cookie', 'co');
// => [
// { text: 'Grab a ', highlighted: false },
// { text: 'co', highlighted: true },
// { text: 'ffee and a ', highlighted: false },
// { text: 'co', highlighted: true },
// { text: 'okie', highlighted: false },
// ]
splitHighlights('Fresh bread and FRESH jam', 'fresh jam');
// => [
// { text: 'Fresh', highlighted: true },
// { text: ' bread and ', highlighted: false },
// { text: 'FRESH', highlighted: true },
// { text: ' ', highlighted: false },
// { text: 'jam', highlighted: true },
// ]
// 'note' and 'book' touch, so they form one segment.
splitHighlights('notebook', 'note book');
// => [{ text: 'notebook', highlighted: true }]
splitHighlights('banana', 'ana');
// => [{ text: 'b', highlighted: false }, { text: 'anana', highlighted: true }]
splitHighlights('Total: $5.00', ' ');
// => [{ text: 'Total: $5.00', highlighted: false }]