Facebook Pixel

Why do you need to escape the query before creating a regex in autocomplete?

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, '\\$&').

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.

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?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.