I am having trouble with the following task:
I need to enrich a string containing html by linking some of the words it contains to "read more" pages. Unfortunately when the search terms I want to replace begin to overlap it becomes tricky. I either end up with nested links or, like in the example below, with longer terms not being replaced.
let html = `<p>So there is this Text in HTML containing words.</p>
<p>I want to link some special words to their read more pages.</p>
<p>But if search terms contain each other they re not linked correctly. Like the ones above.</p>`;
const linkTo = [
{term: 'words', link: 'https://example.com/words'},
{term: 'special words', link: 'https://example.com/special_words'},
];
for(const pair of linkTo){
const re = new RegExp(pair.term, "g");
html = html.replace(re, `<a href="${pair.link}">${pair.term}</a>`);
}
document.body.innerHTML = html;
<html><body></body></html>
In the example above the "special words" in line 2 should link to its own page.
Any Ideas?
Thanks in advance!