Text Search IILoading saved progress…

Text Search II

Implement highlight(text, terms) — scan a string and wrap every occurrence of any term from a list in <mark></mark> tags, the same way a search engine bolds your query words in the results. This is the multi-term version of single-term search: you match all the terms in the list, not just one. Matching is case-insensitive (the term react finds React), but the output keeps the text's original casing. Terms are plain strings, so a character like + or . inside a term must match literally — c++ should find the text c++, not behave like a regular expression.

Signature

// text:  string     — the source text to search within.
// terms: string[]   — the terms to highlight (case-insensitive, matched literally).
// returns: string
//   The same text with each matched span wrapped in <mark>…</mark>.
//   Original casing is preserved; nothing else changes.
function highlight(text, terms): string;

Examples

// Each matched term is wrapped; the original casing ('React') is kept.
highlight('I love React and JavaScript', ['react', 'javascript']);
// → 'I love <mark>React</mark> and <mark>JavaScript</mark>'
// When one term is a prefix of another at the same spot, the longest wins —
// 'javascript' is wrapped whole instead of nesting a 'java' inside it.
highlight('java and javascript', ['java', 'javascript']);
// → '<mark>java</mark> and <mark>javascript</mark>'

Notes

  • Match every term in the list. Build the result so a span matching any term is wrapped. The single-term case is just a list of length one.
  • Case-insensitive match, original-case output. The term react matches React, REACT, or reAct, but the wrapped text is exactly what appeared in the source — you never lowercase the output.
  • Terms are literal, not patterns. A term like c++, a.b, or (x) must match those exact characters. Escape regex-special characters before searching so they lose their special meaning.
  • Longest match wins. When two terms could start at the same position (java and javascript), wrap the longer one. Don't produce nested or partial tags.
  • Don't double-wrap, and handle the empty cases. An empty terms list or empty text returns the text unchanged. Matching is substring-based: cat matches inside category.
Loading editor…