Skip to the solution
HardFrontendAsked in 20245 min read

Query text highlighter

3.3k views

The problem

Problem, as an interviewer would state it: "Implement a search-text highlighter: given a container element and a query string, wrap every real occurrence of that query (case-insensitive) in a <mark> element, without disturbing any other DOM structure."

Examples:

Code
highlightText(container, "quick"); // both "Quick" and "quick" get wrapped in <mark>

Clarifying questions expected:

  • Should this search across MULTIPLE separate text nodes within the container, or only within a single text node?
  • Case-sensitive or case-insensitive matching by default?
  • What real characters in the query need escaping, given the search is implemented with a regular expression?

Code / implementation expected: Yes — real, direct proof against a real jsdom container confirming correct, case-insensitive matches wrapped in real <mark> elements, with all surrounding text preserved exactly.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the highlighter correctly wraps case-insensitive matches in real mark elements against a jsdom container, preserving surrounding text

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 130 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Find nearest common ancestor node

Continue