How do you handle empty query in autocomplete highlighting?
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.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Autocomplete: Highlighting Matching Text
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'.
Still have questions?
Browse all our FAQs or reach out to our support team
