I’m trying to remove all HTML elements from an article and adding a highlight class at the end to highlight the search word. Unfortunately, this regex doesn’t seem to work as expected. According to a different post, a dynamic regex should be passed as a new RegExp()
.
const format = (query, data) => {
// remove all html elements
const output =
data.replace(/<[^>]*>?/gi, "").length > 400
? data.replace(/<[^>]*>?/gi, "").slice(0, 400) + "..."
: data.replace(/<[^>]*>?/gi, "");
//regex
const highlight = new RegExp(String.raw`/${query}/`, "gi");
// add highlight
return output.replace(
highlight,
`<span className="highlight">${query}</span>`
);
};