I wrote a function that replaces every string from a text that is mentioned in an array of strings to a mark down link linking to a word glossary page.
Example:
const text = "This is an example text with an [example](example.com) markdown link.";
const highlightedWords = ["xxx", "example", "yyy"];
const replaceWords = (text: string, highlightedWords: string[]) => {
if (highlightedWords.length == 0 || text == null) {
return text;
}
return text.replace(
new RegExp(`\\b(${highlightedWords.join("|")})\\b`, "gi"),
`[$1](/glossary#$1)`
);
};
console.log(replaceWords(text, highlightedWords));
// Output: This is an [example](/glossary#example) text with an [[example](/glossary#example)]([example](/glossary#example).com) markdown link.
I think you see the problem. I want to achieve, that the regex function ignores the text fragments that already that are already enclosed by any markdown link syntax.
Thanks for your help!