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, '\\$&').
Autocomplete: Highlighting Matching Text
Why do you need to escape the query before creating a regex in autocomplete?
The answer
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.