How to Highlight Search Terms in Results with React
To highlight only the search term in search results, split each string into "matched parts" and "other parts," then render the matched parts wrapped in a <mark> element. The split can be done in one line by passing a regular expression to the string's split. You don't need to build an HTML string and pass it to dangerouslySetInnerHTML.
I made a list of blog post titles with a search box that filters it, and checked how the highlighting works and what happens when it is written the wrong way.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, transformed it with esbuild, operated Chromium with Playwright, and inspected the HTML of each row after typing into the search box. I did not test Firefox, Safari, behavior during IME composition for Japanese input, or the type definitions needed to call RegExp.escape from TypeScript.

- 1. A component that wraps matched parts in mark
- 2. Building a regular expression from the search term
- 3. Changing the color of mark
- 4. Passing input straight into a regular expression makes symbols blank the screen
- 5. Reusing a regular expression with the g flag in test() drops results
- 6. When short words come first, only part of a longer word is highlighted
- 7. Putting highlights in with dangerouslySetInnerHTML executes the HTML inside items
- 8. If RegExp.escape is available, you don't need a custom function
A component that wraps matched parts in mark
The Highlight below is responsible for highlighting. It takes the string to display, text, and a regular expression built from the search term, regExp.
type Props = {
text: string;
regExp: RegExp | null;
};
export function Highlight({ text, regExp }: Props) {
if (!regExp) return text;
// Splitting with a regex wrapped in ( ) puts the matched parts at odd indices.
const parts = text.split(regExp);
return parts.map((part, i) => (i % 2 === 1 ? <mark key={i}>{part}</mark> : part));
}
The key point is to wrap the whole regular expression in ( ). As the MDN explanation of String.prototype.split() describes, if the separator regular expression has a capturing group, the matched parts are also included in the result array. For example, splitting a sample title that means "Listing Cat Photos with React" with /(react)/i gives an array whose first element is an empty string, whose second element is 'React', and whose third element is the rest of the title. So matched parts always land at odd array indices (1, 3, …). All that remains is to wrap only the elements at odd indices in <mark>.
Parts that did not match are returned as plain strings in the array. Running the development build produced no warnings or errors about key.
The MDN explanation of the mark element gives, as an example of when to use <mark>, showing words that match a search.
Building a regular expression from the search term
The function that builds a regular expression from the search box text is shown below. It matches, case-insensitively, any of the words separated by spaces.
// Prefix characters that have special meaning in regex with \.
export function escapeRegExp(text: string) {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Build a regex that matches any of the space-separated words, case-insensitively.
export function toSearchRegExp(query: string): RegExp | null {
const words = query.trim().split(/\s+/).filter(Boolean);
if (words.length === 0) return null;
// Put longer words first (so 'cat tongue' is tried before 'cat').
const pattern = [...words]
.sort((a, b) => b.length - a.length)
.map(escapeRegExp)
.join('|');
return new RegExp(`(${pattern})`, 'i');
}
Here I do three things:
- Put a
\before symbols such as.and+in the input so they are treated as plain characters - Sort the words so longer ones come first
- Give the flags only
i, notg
I checked what happens when each of these is left out in the sections below.
In the list component, the same regular expression is used for both filtering and highlighting. When the search box is empty (or contains only spaces), toSearchRegExp returns null, so all items are shown as they are.
import { useState } from 'react';
import { titles } from './data';
import { Highlight } from './Highlight';
import { toSearchRegExp } from './searchRegExp';
export function App({ items = titles }: { items?: string[] }) {
const [query, setQuery] = useState('');
const regExp = toSearchRegExp(query);
const results = regExp ? items.filter((title) => regExp.test(title)) : items;
return (
<div className="search">
<label>
記事を検索
<input type="search" value={query} onChange={(e) => setQuery(e.target.value)} />
</label>
<p className="count">{results.length}件</p>
<ul>
{results.map((title) => (
<li key={title}>
<Highlight text={title} regExp={regExp} />
</li>
))}
</ul>
</div>
);
}
When I typed "cat cat tongue" into the search box in the test environment, the HTML of the second row was as follows. Both "cat tongue" and "cat" were each wrapped in <mark>.
<mark>猫舌</mark>の<mark>猫</mark>にも分かる useEffect
When I typed "react", "React", "react", and "REACT" were all highlighted, and the original upper and lower case characters remained as they were inside <mark>. On the other hand, searching with full-width letters "react" did not match the half-width "React", and returned 0 results. Similarly, searching for "neko" (hiragana) returned only the rows containing "neko" (hiragana), and rows containing "neko" (katakana) or "cat" (in kanji) did not appear. This article does not implement processing that treats full-width and half-width characters, or hiragana and katakana, as the same.
Changing the color of mark
The appearance of <mark> can be changed with CSS. In the test environment's Chromium, if no CSS was written, the background was yellow (rgb(255, 255, 0)) and the text was black (rgb(0, 0, 0)). If you want the text color to match the surrounding text, write color: inherit.
mark {
background-color: #b8eef7;
color: inherit;
border-radius: 2px;
}
Passing input straight into a regular expression makes symbols blank the screen
I compared a version that passes the input directly to new RegExp() without going through escapeRegExp.
const parts = text.split(new RegExp(`(${query})`, 'i'));
When I typed "." in this version, . was treated as "any one character," and every character in all 8 rows (the list with one extra item in an HTML-like string, used in the dangerouslySetInnerHTML section) was wrapped in <mark> one by one. In the correct version that uses escaping, there is no row containing . among the 7 items in the list, so there are 0 results.
Typing "c++" caused a more serious problem. /(c++)/i is not a valid regular expression, so during rendering an error Invalid regular expression: /(c++)/i: Nothing to repeat was thrown, and the list disappeared from the screen along with the search box (the number of elements inside #root became 0). With the escaped version, "C++" in the sample title about the differences between C++ and TypeScript types is highlighted.
As the MDN regular expression guide explains, to search for characters with special meaning as plain characters, put a \ in front of them. escapeRegExp is the function that goes through the input and adds that \ in front of its symbols.
Reusing a regular expression with the g flag in test() drops results
When I gave the regular expression the g flag and used test() repeatedly inside the filter for filtering, rows that should match were dropped. When I typed "cat" in the test environment, the correct version gave 3 results, but the version with g gave 2. The dropped row was the useEffect row, a sample title meaning roughly "useEffect that even a cat with a sensitive tongue can follow."
// Approach that does not work.
const regExp = query ? new RegExp(`(${escapeRegExp(query)})`, 'gi') : null;
const results = regExp ? titles.filter((title) => regExp.test(title)) : titles;
According to the MDN explanation of RegExp.prototype.test(), with a regular expression that has the g flag, each time test() returns true, lastIndex advances, and the next test() starts searching from that position, even if it is on a different string. After "cat" was found in the first row (the sample title for "Listing Cat Photos with React"), the useEffect row was searched starting right after the position where the match was found in the first row (index 8, the 9th character from the start). The "cat" in the useEffect row is at its first and fourth characters (indices 0 and 3), so it was not found.
split splits at every match even without g. For this reason, toSearchRegExp in this article gives only the i flag.
When short words come first, only part of a longer word is highlighted
I also tried a version that removed the sorting from toSearchRegExp and joined the words in input order, with the shorter word "cat" first. When I typed "cat cat tongue", only the first character, "cat", of "cat tongue" was highlighted in the useEffect row, and "tongue" was left unwrapped.
<mark>猫</mark>舌の<mark>猫</mark>にも分かる useEffect
As the MDN explanation of alternation (|) describes, the alternatives joined by | are tried from left to right, and the first one that matches is used. So at the position of "cat tongue", "cat" matched first, and the rest of the word was not wrapped. Sorting from long to short puts the longer word first, so "cat tongue" is wrapped as a whole (as in the HTML in the previous section).
Putting highlights in with dangerouslySetInnerHTML executes the HTML inside items
You can also insert <mark>$1</mark> with the string replace method and pass the resulting string to dangerouslySetInnerHTML. However, with this approach, the item string itself is also treated as HTML.
// Approach that does not work.
const html = text.replace(new RegExp(`(${escapeRegExp(query)})`, 'gi'), '<mark>$1</mark>');
return <span dangerouslySetInnerHTML={{ __html: html }} />;
I mixed one item with the string <img src="x" onerror="window.__xss = true"> into the list and tried it. Just opening the page created an img element, the code written in onerror ran, and window.__xss became true. When the same item was displayed with Highlight in this article, no img element was created, and the string appeared on the screen as it was. When I searched for "img", only the "img" inside that string was wrapped in <mark>.
If you pass untrusted strings, such as text written by users, to dangerouslySetInnerHTML, scripts inside them may run (XSS). The React official reference on dangerouslySetInnerHTML also says to use it only with data that is trusted and sanitized. If you write search highlighting to return elements as this article does, you avoid building HTML strings at all.
If RegExp.escape is available, you don't need a custom function
A function that escapes symbols has been added to standard JavaScript as RegExp.escape(). The MDN explanation of RegExp.escape() recommends using it instead of writing the process of adding \ yourself. According to MDN's compatibility data, it is available from Chrome 136, Firefox 134, Safari 18.2, and Node.js 24.0.0.
In the test environment, Chromium 153 had RegExp.escape, and Node.js 22.22.0 did not. In Chromium, for six search terms, "react", "c++", "cat cat tongue", ".", "(", and "a|b", I split the seven list items using a regular expression built with escapeRegExp and one built with RegExp.escape, and confirmed that the results were all the same. RegExp.escape('react') rewrites the leading letter as something like \x72eact, but the strings it matches do not change.
While some users are on browsers that do not support RegExp.escape, use escapeRegExp from this article. Another option is to use RegExp.escape only when it exists, and switch to the custom function when it does not.





