Replace specific words with markdown links in a text

Issue

I’ve got a text saved in a longer string and want to replace some words of the text with a highlighted version or a markdown link to a glossary page where the words are described. The words that should be filtered are stored in a string array.

At the moment my code looks something like this:

const text = "Lorem ipsum xxx dolor sit amet."
const highlightedWords = ["xxx", "yyy"]

const newText = text.replace(new RegExp(highlightedWords.join("|"), "gi"), "[same-word-here]('/glossary#same-word-here)');

The part with same-word-here should be the same word that was replaced before, but I don’t know how to get this one in this position.

If you need a better known example: It should look like a linked article in a wikipedia text

Thanks for your help.

Solution

Wrap the the expression in a capture group (), and then use $1 to use the capture group’s content. You should also use \b (word boundary) to prevent text replacement when it’s in another work, for example "xxxzzz".

const text = "Lorem ipsum xxx dolor sit amet."
const highlightedWords = ["xxx", "yyy"]

const newText = text.replace(new RegExp(`\\b(${highlightedWords.join("|")})\\b`, "gi"), "[$1]('/glossary#same-word-here)'");

console.log(newText)

Answered By – Ori Drori

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.