I have a string containing multiple sentences, and I want to highlight specific words and special characters in that string. The words (combined with special characters) are stored in an array. To highlight the words I wrap the HTML-tag around the matched words in the string. However, when one of the words I want to highlight contains a special character or a period (.) the word is not matched. Here is my code:
const words = ["Hello", "dog", "etc.", "»", "«"];
const applyHighlights = (text) => {
words.forEach((word) => {
let re = new RegExp(`\\b${word}\\b`, "gi");
text = text.replace(/\n$/g, "\n\n").replace(re, "<mark>$&</mark>");
});
return text;
};
applyHighlights("Hello I am a dog etc. »are you?«");
This returns: <mark>Hello</mark> I am a <mark>dog</mark> etc. »are you?«
and not:
<mark>Hello</mark> I am a <mark>dog</mark> <mark>etc.</mark> <mark>»</mark>are you?<mark>«</mark>
as I expect it to.
What am I doing wrong here? Why is it only matching occurrences made up of "real" letters and not special characters like ?, ., - or any string that contain a special character for that matter.