Facebook Pixel

How do you highlight multiple matches in an autocomplete?

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.

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

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.