Text SearchLoading saved progress…

Text Search

Implement textSearch(text, term) — scan a string and wrap every occurrence of a single search term in <mark></mark> tags, the way a browser's find-on-page highlights the word you searched for. Matching is case-insensitive (the term react finds React), but the output keeps the text's original casing. The term is a plain string, so a character like + or . inside it must match literally — a.b should find the text a.b, not behave like a regular expression.

Signature

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

Examples

// The one occurrence of 'cat' is wrapped; everything else is untouched.
textSearch('the cat sat', 'cat');
// → 'the <mark>cat</mark> sat'
// Case-insensitive match, but the original 'React' casing is kept in the output.
textSearch('React is great', 'react');
// → '<mark>React</mark> is great'

Notes

  • Wrap every occurrence. Each place the term appears gets its own <mark></mark> pair. Adjacent matches are wrapped separately: textSearch('aaa', 'a') is <mark>a</mark><mark>a</mark><mark>a</mark>.
  • 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.
  • The term is literal, not a pattern. 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.
  • Handle the empty cases. An empty term (or empty text) returns the text unchanged — don't wrap a zero-length match.
  • Substring matching. The term matches anywhere, even inside a larger word: cat matches inside category.
  • Single term only. This is the single-term highlighter; matching a list of terms at once is the related Text Search II problem.
Loading editor…