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 this post, a dynamic regex should be passed as a new RegExp()
.
const article = "some article content";
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>`
);
};
HTML:
<p className="paragraph--s">{format(searchTag, article)}</p>
2
Answers
This function works without a loop. The key was to remove the backslashes from the regex and save each step in a separate variable.
The function takes two parameters: text, which is the text you want to search, and words, an array of words you want to highlight. It can handle multiple words in the text.
I originally posted PHP code not realizing you needed JavaScript. Here’s translation.