Facebook Pixel

Autocomplete: Highlighting Matching Text

Highlight the matching portion of each suggestion. Here is how to implement it.

Autocomplete: Highlighting Matching Text

Highlighting the matching portion of each suggestion improves UX. Here is how.

Implementation

function highlightMatch(text, query) { if (!query) return text; const regex = new RegExp(`(${escapeRegex(query)})`, "gi"); return text.replace(regex, "<strong>$1</strong>"); } function escapeRegex(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }

Usage

suggestions.innerHTML = items.map((item) => ` <li class="suggestion-item">${highlightMatch(item, query)}</li> `).join("");

CSS

.suggestion-item strong { color: #007bff; font-weight: bold; }

Example

Query: "app"

  • "apple" -> "apple" (app is highlighted)
  • "pineapple" -> "pineapple" (app is highlighted)
  • "application" -> "application" (app is highlighted)

Edge Cases

  • Empty query: return the text as-is.
  • Special characters in query: escape them for regex.
  • Case-insensitive matching: use the i flag.
  • Multiple matches: all are highlighted (global flag g).

The Takeaway

Highlight matching text: escape the query for regex, create a case-insensitive global regex, replace matches with <strong>$1</strong>. Style strong with a different color. Handle edge cases (empty query, special characters, multiple matches). This improves the autocomplete UX significantly.

Use a regex to wrap the matching part in a <strong> tag: text.replace(new RegExp(`(${escapeRegex(query)})`, 'gi'), '<strong>$1</strong>'). Style strong with a different color. Use 'gi' flags for global, case-insensitive matching.

Because the query may contain special regex characters (., *, +, ?, etc.). If not escaped, they would be interpreted as regex syntax, causing errors or incorrect matches. Escape with string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').

Use the 'i' flag in the regex: new RegExp(`(${query})`, 'gi'). The 'i' flag makes the match case-insensitive, so 'app' matches 'Apple', 'APPLE', and 'apple'.

Use the 'g' (global) flag in the regex. This replaces all matches, not just the first. For example, 'banana' with query 'an' would highlight both 'an' occurrences: b<strong>an</strong><strong>an</strong>a.

If the query is empty, return the text as-is (no highlighting). Check at the start of the function: if (!query) return text. This avoids creating an empty regex, which matches everything.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.