AI solution for JavaScript Coding Question on BFE.dev
55. highlight keywords in HTML string
Here's a possible solution:
function highlightKeywords(html, keywords) { // Create a regular expression that matches all keywords, // taking care of word boundaries (\b) and case-insensitivity (i flag) const regex = new RegExp("\\b(" + keywords.join("|") + ")\\b", "gi"); // Replace all occurrences with the same text, wrapped in <em> tags return html.replace(regex, "<em>$1</em>");}
Explanation:
-
We create a regular expression using the
RegExp
constructor, by joining all keywords with|
(which means "or" in regex), and wrapping them between\b
to ensure only whole words match (i.e. not part of a longer word). We also pass thegi
flags to make the match case-insensitive and global (i.e. find all matches, not just the first one). -
We call the
replace
method of thehtml
string with theregex
and a replacement string"<em>$1</em>"
, which means "replace the matched string with itself ($1
), wrapped in<em>
tags".
Note that this solution should work correctly for overlapping and adjacent keywords because we're using a global regex (which finds all matches) and the tags are non-nesting (i.e. can be safely applied multiple times without interfering with each other).