We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A hard frontend problem, graded against 6 test cases (3 of them hidden).
React and browser-platform problems - hooks, event handling, and rendering behaviour.
Reach for it when you see: A component, hook, or DOM-behaviour question rather than an algorithm.
More Frontend problems →The naive answer - `root.innerHTML = root.innerHTML.replace(/cat/gi, "<mark>$&</mark>")` - fails three of the tests: it rewrites the `title="cat"` attribute, it would corrupt a tag if the term appeared in one, and it throws away every listener and reference on the existing nodes.
The right tool is a `TreeWalker` restricted to `SHOW_TEXT`. Collect the text nodes first (mutating during traversal is a classic footgun), then for each node with a match: split its `data` around the matches, build the replacement as a `DocumentFragment` of plain text nodes and `<mark>` elements, and `replaceWith` it. Elements are never touched, so `<b>` and `<a title>` survive intact.
Two details the hidden tests pin: escape the term before building the RegExp (`a.b` is literal), and take the matched slice from the node (`Cat` stays `Cat`), not from `term`.
Time: O(total text length). Space: O(matches).
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.