A search box filters a list, and each result shows the matching part in bold or with a yellow background: type "react" and "Learn React today" lights up. It looks like a one-line replace, but it is not. The words may overlap, the query may contain characters such as + or (, and the text comes from users, so the result must be safe HTML.
Write highlight(text, query) in highlight.js. It returns the text as HTML, with every match of the query's words wrapped in <mark> and </mark>.
Every occurrence of every word of the query is marked, not only the first. Matching ignores case, but the output keeps the text's own letters.
The query is split on whitespace; empty words are ignored. An empty or blank query marks nothing.
Overlapping matches, of one word or of different words, and matches that touch (one ends where the next starts) become a single <mark>. Matches with any character between them stay separate.
The query's characters are plain text: ., *, +, ( and $ match only themselves.
The text is escaped, inside and outside the marks: & to &, < to <, > to >, " to ", ' to '.
Matches are found in the original text, never in the escaped HTML: the query amp does not match inside &, and the query < marks a < character.
Long texts with many matches are handled in well under a second.
Plain JavaScript in a browser page; the tests call the global highlight from highlight.js.
Case is compared with toLowerCase(). Letters whose lower case has a different length (such as the Turkish dotted capital I) are out of scope, as are whole-word matching and accents.